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

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

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

if [[ "${cloud}" == "gcp" && -z "${gcp_service_account}" ]]; then
  echo "gcp_service_account is required when cloud=gcp"
  exit 1
fi

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

if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    SED_IN_PLACE=(-i '')
else
    # Linux and others
    SED_IN_PLACE=(-i)
fi

find "${deploy_dir}" -type f -exec sed "${SED_IN_PLACE[@]}" "s|TMPL_IRSA_ROLE_ARN|${irsa_role_arn}|g" {} \;
find "${deploy_dir}" -type f -exec sed "${SED_IN_PLACE[@]}" "s|TMPL_CERT_MANAGER_CLIENT_ID|${cert_manager_client_id}|g" {} \;
if [[ -n "${gcp_service_account}" ]]; then
  find "${deploy_dir}" -type f -exec sed "${SED_IN_PLACE[@]}" "s|TMPL_GCP_SERVICE_ACCOUNT|${gcp_service_account}|g" {} \;
fi
