#!/usr/bin/env bash
set -euo pipefail
# When changing this script, remember to modify the corresponding github action
logicalRegionName=${1}
env=${2}
cloud=${3}
image_registry=${4}

ROOT=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)
deploy_dir="${ROOT}/envs/${env}-${logicalRegionName}"
variant_dir="${ROOT}/variants/${env}-${cloud}"

if [ -e ${deploy_dir} ]; then
  echo "New region deploy directory already exist"
else
  mkdir -p "${deploy_dir}"
fi

echo "Prepare manifest files"
cp "${variant_dir}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"
cp "${variant_dir}/version_tmpl.yaml" "${deploy_dir}/version.yaml"

# https://stackoverflow.com/questions/4247068/sed-command-with-i-option-failing-on-mac-but-works-on-linux
if [[ "$OSTYPE" == "darwin"* ]]; then
  # Require gnu-sed.
  if ! [ -x "$(command -v gsed)" ]; then
    echo "Error: 'gsed' is not istalled." >&2
    echo "If you are using Homebrew, install with 'brew install gnu-sed'." >&2
    exit 1
  fi
  SED_CMD=gsed
else
  SED_CMD=sed
fi

${SED_CMD} -i "s|IMAGE_REGISTRY|${image_registry}|g" "${deploy_dir}/version.yaml"
