#!/bin/bash
set -euo pipefail
# When changing this script, remember to modify the corresponding github action
vendor=${1}
env=${2}
region=${3}
logical_region=${4}
cluster=${5}
json_file_path=${6}
args=$(jq -r '.' "${json_file_path}")

alertmanager_role_arn=$(echo ${args} | jq -r '.alertmanagerRoleArn')
nginx_read_ingress_class=$(echo ${args} | jq -r '.nginxReadIngressClass')
hosted_zone_name=$(echo ${args} | jq -r '.hostedZoneName')
image_registry=$(echo ${args} | jq -r '.imageRegistry')
clinic_private_dns=$(echo ${args} | jq -r '.clinicPrivateDNS')
clinic_secret_name=$(echo ${args} | jq -r '.clinicSecretName')
byoc=$(echo ${args} | jq -r '.byoc')
tenant=$(echo ${args} | jq -r '.tenantID')

ROOT=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)
deploy_dir="${ROOT}/envs/${env}"
deploy_file="${deploy_dir}/regional-${vendor}-${logical_region}.yaml"
variant_dir="${ROOT}/variants"
mkdir -p ${deploy_dir}

tmpl_values_file="${variant_dir}/${env}-${vendor}-values-tmpl.yaml"
if [ "$byoc" == "true" ]; then
  tmpl_values_file="${variant_dir}/${env}-${vendor}-byoc-values-tmpl.yaml"
  if grep -q 'TMPL_CLINIC_SECRET_NAME' "${tmpl_values_file}" && { [ -z "$clinic_secret_name" ] || [ "$clinic_secret_name" == "null" ]; }; then
    echo "Error: clinicSecretName is required when byoc=true" >&2
    exit 1
  fi
fi

if [ -e ${deploy_file} ]; then
  echo "New region deploy file already exist, skip it"
else
  echo "Prepare manifest files"
  cp "${tmpl_values_file}" "${deploy_file}"
  sed -i "s|TMPL_CLUSTER_NAME|${cluster}|g" ${deploy_file}
  sed -i "s|TMPL_NGINX_READ_INGRESS_CLASS|${nginx_read_ingress_class}|g" ${deploy_file}
  sed -i "s|TMPL_REGION|${logical_region}|g" ${deploy_file}
  sed -i "s|TMPL_LOGICAL_REGION|${logical_region}|g" ${deploy_file}
  sed -i "s|TMPL_TENANT|${tenant}|g" ${deploy_file}
  sed -i "s|TMPL_HOSTED_ZONE_NAME|${hosted_zone_name}|g" ${deploy_file}
  sed -i "s|TMPL_ALERTMANAGER_ROLE_ARN|${alertmanager_role_arn}|g" ${deploy_file}
  sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" ${deploy_file}
  sed -i "s|TMPL_CLINIC_PRIVATE_DNS|${clinic_private_dns}|g" ${deploy_file}
  sed -i "s|TMPL_CLINIC_SECRET_NAME|${clinic_secret_name}|g" ${deploy_file}
fi
