#!/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}")

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

nginx_read_ingress_class=$(echo ${args} | jq -r '.nginxReadIngressClass')
clinic_private_dns=$(echo ${args} | jq -r '.clinicPrivateDNS')
clinic_secret_name=$(echo ${args} | jq -r '.clinicSecretName')
byoc=$(echo ${args} | jq -r '.byoc')
image_registry=$(echo ${args} | jq -r '.imageRegistry')

tmpl_values_file="${variant_dir}/${vendor}-values-tmpl.yaml"
if [ "$byoc" == "true" ]; then
  tmpl_values_file="${variant_dir}/${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_dir} ]; then
  echo "New region deploy dir already exist, skip it"
else
  mkdir -p ${deploy_dir}
  echo "Prepare manifest files"
  cp "${tmpl_values_file}" "${deploy_file}"
  sed -i "s|TMPL_NGINX_READ_INGRESS_CLASS|${nginx_read_ingress_class}|g" ${deploy_file}
  sed -i "s|TMPL_ENV|${env}|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}
  sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" ${deploy_file}
fi
