#!/usr/bin/env bash

set -euo pipefail

function usage() {
  cat <<EOF
Usage:
    $0 [-f] [-m <message>] my_image
Arguments:
    -f: Force publication even if there are uncommitted changes
    -m: Specify an optional message in the Slack update
EOF
}

for arg in "$@"; do
  if [ "$arg" == --help ] || [ "$arg" == -h ]; then
    usage
    exit 0
  fi
done

message=
force=
while getopts ":m:f" opt; do
  case $opt in
    m)
      message=$OPTARG
      ;;
    f)
      force=1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      usage >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      usage >&2
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

image_name="$1"

# Change directories to the top of the repository
builtin cd "$(dirname "${BASH_SOURCE[0]}")"
git_workspace="$(git rev-parse --show-toplevel)"
builtin cd "$git_workspace"

# Abort if there are uncommitted changes. Otherwise, it will be hard
# for others to know what code was actually being deployed.
git_changes="$(git status --untracked-files=no --porcelain)"
if [ -z "$force" ] && [ ! -z "$git_changes" ]; then
  echo Uncommitted changes in git repo detected. Aborting! >&2
  exit 1
fi

git_hash=$(git rev-parse --short HEAD)
git_branch=$(git rev-parse --abbrev-ref HEAD)
echo "Building $image_name using git branch $git_branch ($git_hash)" >&2

latest_tag="$(data/ingest/docker_images/get_latest_tag.py "$image_name")"
next_tag=$((latest_tag+1))
environ=prod
echo "Building and deploying image '$image_name' in environ '$environ' with new version '$next_tag'" >&2
data/ingest/docker_images/build_and_push_ingest_job.sh "$image_name" "$environ" "$next_tag"

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

  if [ ! -z "$message" ]; then
    echo Message: $message
  fi
}

# 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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
