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

additional_args=$(jq -r '.' "${json_file_path}")

echo "additional_args: ${additional_args}"
image_registry=$(echo ${additional_args} | jq -r '.imageRegistry')

if [[ "$OSTYPE" == "darwin"* ]]; then
  if ! [ -x "$(command -v gsed)" ]; then
    echo "Error: 'gsed' is not installed." >&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

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

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

mkdir -p "${deploy_dir}"
echo "Prepare vector manifest files"
cp "${variant_dir}/values_tmpl.yaml" "${deploy_dir}/values.yaml"

find "${deploy_dir}" -type f -exec ${SED_CMD} -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" {} \;
