#!/bin/bash
set -euo pipefail

# When changing this script, remember to modify the corresponding github action
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source "${ROOT}/../../lib/lib.sh"

vendor=${1}
env=${2}
region=${3}
logical_region=${4}
cluster=${5}
json_file_path=${6}
args=$(jq -r '.' "${json_file_path}")

if [[ "${vendor}" != "azure" ]]; then
  exit 0
fi

byoc=$(echo "${args}" | jq -r '.byoc // "false"')
if [[ "${byoc}" != "true" ]]; then
  exit 0
fi

agic_application_gateway_id=$(echo "${args}" | jq -r '.agicApplicationGatewayID // empty')
agic_application_gateway_name=$(echo "${args}" | jq -r '.agicApplicationGatewayName // empty')
agic_application_gateway_resource_group=$(echo "${args}" | jq -r '.agicApplicationGatewayResourceGroup // empty')
agic_subscription_id=$(echo "${args}" | jq -r '.agicSubscriptionID // empty')
agic_identity_client_id=$(echo "${args}" | jq -r '.agicIdentityClientID // empty')
image_registry=$(echo "${args}" | jq -r '.imageRegistry // empty')

for required_arg in \
  agic_application_gateway_id \
  agic_application_gateway_name \
  agic_application_gateway_resource_group \
  agic_subscription_id \
  agic_identity_client_id \
  image_registry; do
  if [[ -z "${!required_arg}" ]]; then
    echo "Error: ${required_arg} is required for Azure BYOC AGIC." >&2
    exit 1
  fi
done

deploy_dir="${ROOT}/envs/${env}-${vendor}-${logical_region}"
deploy_file="${deploy_dir}/values.yaml"
variant_dir="${ROOT}/variants"

if [[ -d "${deploy_dir}" ]]; then
  echo "New region deploy file already exist, skip it"
else
  mkdir -p "${deploy_dir}"
  echo "Prepare manifest files"
  cp "${variant_dir}/azure-byoc-values-tmpl.yaml" "${deploy_file}"

  replace_token "TMPL_AGIC_APPLICATION_GATEWAY_ID" "${agic_application_gateway_id}" "${deploy_file}"
  replace_token "TMPL_AGIC_APPLICATION_GATEWAY_NAME" "${agic_application_gateway_name}" "${deploy_file}"
  replace_token "TMPL_AGIC_APPLICATION_GATEWAY_RESOURCE_GROUP" "${agic_application_gateway_resource_group}" "${deploy_file}"
  replace_token "TMPL_AGIC_SUBSCRIPTION_ID" "${agic_subscription_id}" "${deploy_file}"
  replace_token "TMPL_AGIC_IDENTITY_CLIENT_ID" "${agic_identity_client_id}" "${deploy_file}"
  replace_token "TMPL_IMAGE_REGISTRY" "${image_registry}" "${deploy_file}"
fi
