#!/usr/bin/env bash

set -euo pipefail

if [[ -z "${1:-}" || "$1" == '--help' || "$1" == '-h' ]]; then
  echo "Usage: $0 TAG"
  exit 1
fi

tag="$1"
chum_to_json_image_name="docker-registry.zooxlabs.com/chum-to-json:$tag"
health_reporter_image_name="docker-registry.zooxlabs.com/chum-to-json-health-reporter:$tag"

cd "$( (builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) )"

cleanup() {
  if [ -f "documentation.html" ]; then
    echo "Not generated" > documentation.html
  fi
}

trap cleanup EXIT

./generate_documentation.sh

(
  set -x
  bazel build -c opt --config=cuda //argus/chum_to_json_service:service_image.tar
  bazel build -c opt --config=cuda //infra/annotator_db/public_util:service_health_reporter_image.tar

  docker load -i $(bazel info -c opt --config=cuda bazel-bin)/argus/chum_to_json_service/service_image.tar
  docker load -i $(bazel info -c opt --config=cuda bazel-bin)/infra/annotator_db/public_util/service_health_reporter_image.tar

  docker tag bazel/argus/chum_to_json_service:service_image "$chum_to_json_image_name"
  docker tag bazel/infra/annotator_db/public_util:service_health_reporter_image "$health_reporter_image_name"

  docker push "$chum_to_json_image_name"
  docker push "$health_reporter_image_name"
)

cleanup

echo Success!
