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

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

echo "additional_args: ${additional_args}"

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

dnsZone=$(echo ${additional_args} | jq -r '.dnsZone')
hostedZoneID=$(echo ${additional_args} | jq -r '.hostedZoneID')
controlplaneSubscriptionID=$(echo ${additional_args} | jq -r '.controlplaneSubscriptionID')
hostedZoneResourceGroup=$(echo ${additional_args} | jq -r '.hostedZoneResourceGroup')
certManagerClientID=$(echo ${additional_args} | jq -r '.certManagerClientID')
gcpProject=$(echo ${additional_args} | jq -r '.gcpProject // .controlplaneProject // empty')

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

if [[ "${cloud}" == "gcp" && ( -z "${gcpProject}" || "${gcpProject}" == "null" ) ]]; then
  echo "gcpProject (or controlplaneProject) is required when cloud=gcp"
  exit 1
fi

mkdir "${deploy_dir}"
echo "Prepare manifest files"
cp "${variant_dir}/letsencrypt-issuer_tmpl.yaml" "${deploy_dir}/letsencrypt-issuer.yaml"
cp "${variant_dir}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"

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

sed "${SED_IN_PLACE[@]}" "s|TMPL_REGION|${region}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_DNS_ZONE|${dnsZone}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_HOSTED_ZONE_ID|${hostedZoneID}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_CONTROLPLANE_SUBSCRIPTION_ID|${controlplaneSubscriptionID}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_HOSTED_ZONE_RESOURCE_GROUP|${hostedZoneResourceGroup}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_CERT_MANAGER_CLIENT_ID|${certManagerClientID}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
sed "${SED_IN_PLACE[@]}" "s|TMPL_GCP_PROJECT|${gcpProject}|g" "${deploy_dir}/letsencrypt-issuer.yaml"
