#!/usr/bin/env bash
set -euo pipefail

root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
pulumi_dir="${root_dir}/deploy/aws"
region=${REGION:-"$(pulumi -C "${pulumi_dir}" config get aws:region)"}
project=${PROJECT:-"$(pulumi -C "${pulumi_dir}" config get project)"}
components=${BUILD_COMPONENTS:-"all"}
IMAGE_TAG=${IMAGE_TAG:-"$(git rev-parse --short HEAD)"}
# Pulumi will only update the deployment if the tag changes.
# So it won't deploy the latest dirty changes we need.
# A simple approach would be to add a timestamp.
# Below is a proper approach that gets a git hash of dirty changes.
# It will work for example when deploying components one-by-one without making changes.
# Ignore tools and deploy directories, the dependency files will be changed during build
if ! git diff --quiet -- ':!deploy' ':!tools' && [ "$project" != "nightly" ] && [ "$project" != "stability" ] && [ "$project" != "staging" ] && [ "$project" != "prod" ]; then
  cp .git/index /tmp/git_index
  export GIT_INDEX_FILE=/tmp/git_index
  git add -u
  IMAGE_TAG="$IMAGE_TAG-$(git write-tree)"
fi

echo "Build $components components for project $project in region $region using image tag: ${IMAGE_TAG}"
IMAGE_TAG=${IMAGE_TAG} PROJECT=${project} ${root_dir}/build-component.sh -c "${components}" -r "${region}"


function remove_server_image_tag() {
  echo "removing dbaas:server_image_tag now because you might forget later"
  pulumi -C "${pulumi_dir}" config rm dbaas:server_image_tag
}

UPDATE_PULUMI=${UPDATE_PULUMI:-""}
if [[ -z $UPDATE_PULUMI ]] ; then
  echo "Build succeed, execute the command below to specify pulumi dbaas image_tag:"
  echo "pulumi -C ${pulumi_dir} config set dbaas:image_tag ${IMAGE_TAG}"
else
  echo "Build succeed, updating pulumi because UPDATE_PULUMI is set"
  if [[ "$components" == "server" ]] ; then
    echo "updating just the server image tag"
    pulumi -C "${pulumi_dir}" config set dbaas:server_image_tag "${IMAGE_TAG}"
    trap remove_server_image_tag EXIT
  else
    echo "updating just the image tag"
    pulumi -C "${pulumi_dir}" config set dbaas:image_tag "${IMAGE_TAG}"
  fi

  pulumi -C "${pulumi_dir}" up --yes
fi
