#!/usr/bin/env bash
#
# Build and push registrar_image

set -euo pipefail

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

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

ingest_docker_images_root="../docker_images"

bash "${ingest_docker_images_root}/ingest_pipeline_base/pull.sh" > /dev/null
bash "${ingest_docker_images_root}/ingest_pipeline_py3_base/pull.sh" > /dev/null

environ="$1"; shift
version="$1"; shift
image="registrar_image"
root_path="data/ingest/registrar"
dest_path="ingest.docker.zooxlabs.com/${root_path}"
git_hash=$(git rev-parse --short HEAD)
git_branch=$(git rev-parse --abbrev-ref HEAD)
git_changes="$(git status --untracked-files=no --porcelain)"
bazel_run "//${root_path}:${image}" -- --norun

docker run "bazel/${root_path}:${image}" -h
if [ $? -ne 0 ]; then
  echo "The image target failed to run. Please fix the issue before pushing the image."
  exit 1
fi

# Tag the image with version and environment
docker tag "bazel/${root_path}:${image}" "${dest_path}/${image}:${version}"
docker push "${dest_path}/${image}:${version}"

docker tag "${dest_path}/${image}:${version}" "${dest_path}/${image}:${environ}"
docker push "${dest_path}/${image}:${environ}"

function notification() {
  local_git_changes=""
  if [ ! -z "$git_changes" ]; then
    local_git_changes=" (contains local changes!)"
  fi
  echo @$LOGNAME pushed image \`registrar_image\`
  echo Tags: \`$environ\`, \`$version\`
  echo Software: \`$git_branch\`, \`$git_hash\`$local_git_changes
}

# Notify slack via the RDP Deploy Logbot integration.
# https://api.slack.com/apps/A018WLW44CS (managed under acheng's account)
notification="$(notification)"
echo "Posting to #rdp-deploys: $notification" >&2
curl --fail --silent --show-error --location \
  --request POST \
  --header 'Content-type: application/json' \
  --data "{\"text\":\"${notification}\"}" \
  https://hooks.slack.com/services/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

