#!/usr/bin/env bash

# This will:
# 1. Build the given web_app with bazel
# 2. Package it along with all of its runtime dependencies
# 3. Build a docker image out of the result
#
# Prerequisites:
# In your web_app directory you will need a properly constructed Dockerfile that:
#  - has a working python environment
#  - installs your web_apps requirements if provided
#      (i.e. pip install -r requirements.txt)
#  - copies in the tar file this script generates that has your bazel-built webapp:
#      `ADD <web_app_name>.tar /`
#  - an entrypoint.sh that does any other setup that should happen at start time
#    and starts your webapp
#
# The `entrypoint.sh` file is required. Those and the
# Dockerfile should be added to the `data` argument of your server's bazel
# target.
#
# A `docker-compose.yml` file that uses your image is optional.
# A `requirements.txt` file is optional.
# A `pip.conf` file is optional.
#
# See web_apps/pipedream_dashboard for an example.

if [ $ZOOX_WORKSPACE_ROOT ]; then
    cd $ZOOX_WORKSPACE_ROOT
fi
if [ ! -f WORKSPACE ]; then
  echo "Must be run from the root of the repository!"
  exit 1
fi

rebuild=" "
if [[ "$1" != "" ]]; then rebuild="--no-cache"; fi
cmd_name=$(basename "$0")
webapp_dir="web_apps/dad"
webapp_name="dad"
bazel_target="dad"
workspace_dir=$(pwd)

#if [ $# != 3 ] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
#    cat <<EOF
#usage: $cmd_name [-h] web_app bazel_target
#
#positional arguments:
#  web_app_dir   directory of your web app relative to $ZOOX_WORKSPACE_ROOT
#  web_app       web_app name to Docker-ize
#  bazel_target  bazel target that runs the web apps's server
#
#optional arguments:
#  -h, --help    show this help message and exit
#EOF
#    exit 1
#fi

set -euo pipefail

bazel build //${webapp_dir}:${bazel_target}
(
  bin_dir="bazel-bin/"
  docker_workspace="${webapp_name}-docker"
  docker_image="docker-registry.zooxlabs.com/${webapp_name}"
  tar_name="${webapp_name}.tar"
  tar_path="${docker_workspace}/${tar_name}"
  cd "$bin_dir"
  mkdir -p ${docker_workspace}
  cp ${webapp_dir}/${bazel_target}.runfiles/zoox/${webapp_dir}/Dockerfile ${docker_workspace}
  cp ${webapp_dir}/${bazel_target}.runfiles/zoox/${webapp_dir}/entrypoint.sh ${docker_workspace}
  tar --dereference -cf "$tar_path" ./${webapp_dir}
  cd "${docker_workspace}"
  docker build . -t ${docker_image} ${rebuild}
  cd "${workspace_dir}"

  echo ""
  echo "Docker image built as ${docker_image}"
  if [ -f "${webapp_dir}/docker-compose.yml" ]; then
      echo "To run locally:"
      echo -e "\tdocker-compose -f ${workspace_dir}/${webapp_dir}/docker-compose.yml up"
  fi
  echo "To push the image to the registry:"
  echo -e "\tdocker push ${docker_image}"
  echo "To tag/version this new image:"
  echo -e "\tdocker tag ${docker_image} ${docker_image}:<new_version>"
  echo -e "\tdocker push ${docker_image}:<new_version>"
)
