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

is_byoc=$(echo "${args}" | jq -r '.isByoc // .byoc // false')

external_dns_role_arn=$(echo ${args} | jq -r '.externalDNSRoleArn')
image_registry=$(echo ${args} | jq -r '.imageRegistry')
hosted_zone_name=$(echo ${args} | jq -r '.hostedZoneName')
hosted_zone_id=$(echo ${args} | jq -r '.hostedZoneId')

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"

# only deploy for aws
if [ "${vendor}" != "aws" ]; then
  exit 0
fi

# AWS BYOC O11Y uses the regional DNS name generated by the Interface Endpoint.
# It must not create records in a customer-provided O11Y Hosted Zone.
if [ "${is_byoc}" = "true" ]; then
  echo "Skip external-dns for AWS BYOC region ${logical_region}"
  exit 0
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 "${variant_dir}/${env}/values-${vendor}-tmpl.yaml" "${deploy_file}"
  sed -i "s|TMPL_EXTERNAL_DNS_ROLE_ARN|${external_dns_role_arn}|g" ${deploy_file}
  sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" ${deploy_file}
  sed -i "s|TMPL_HOSTED_ZONE_NAME|${hosted_zone_name}|g" ${deploy_file}
  sed -i "s|TMPL_HOSTED_ZONE_ID|${hosted_zone_id}|g" ${deploy_file}
fi
