#!/usr/bin/env bash

set -euo pipefail

script_directory="$(builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(builtin cd "$script_directory" && git rev-parse --show-toplevel)"
environment="${1:-production}"

cd "$repo_root"

bazel --nohome_rc test //ci/metrics/...

read -p "Deploy to $environment? [y/n] "
echo

if [[ $REPLY != 'y' ]]; then
  exit 1
fi

docker_tag="$environment-$(date '+%Y%m%dT%H%M%S')"

echo Pushing image to $docker_tag...
bazel --nohome_rc run --define ci_metrics_image_tag="$docker_tag" //ci/metrics:push_metrics_image

echo Applying kubernetes yaml...
# Do some basic templating to replace the docker tag.
cat ci/metrics/cron.yaml |
  sed "s/{{DOCKER_TAG}}/$docker_tag/g" |
  kubectl apply --context dev-aws --namespace ci-cronjobs --filename -
