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

# Ensure jq is installed
if ! command -v jq &> /dev/null; then
    echo "jq could not be found. Please install jq to continue."
    exit 1
fi

# Parse JSON and assign variables
# If the key is not found, assign an empty string
assume_role_name=$(jq -r '.assume_role_name // ""' "${json_file_path}")
readonly_assume_role_name=$(jq -r '.readonly_assume_role_name // ""' "${json_file_path}")
aws_cluster_server_role_arn=$(jq -r '.aws_cluster_server_role_arn // ""' "${json_file_path}")
irsa_role_arn=$(jq -r '.irsa_role_arn // ""' "${json_file_path}")
global_role_arn=$(jq -r '.global_role_arn // ""' "${json_file_path}")
image_registry=$(jq -r '.image_registry // ""' "${json_file_path}")
config_change_env=$(jq -r '.config_change_env // "dev"' "${json_file_path}")
config_change_activity_enabled=$(jq -r '.config_change_activity_enabled // "false"' "${json_file_path}")
config_change_activity_hub_ep=$(jq -r '.config_change_activity_hub_ep // "https://b9u12esjuf.execute-api.us-west-2.amazonaws.com"' "${json_file_path}")
config_change_activity_source=$(jq -r '.config_change_activity_source // "gitops"' "${json_file_path}")
config_change_activity_clinic_ep=$(jq -r '.config_change_activity_clinic_ep // "http://clinic-dev-1923272735.us-west-2.elb.amazonaws.com:8085"' "${json_file_path}")
cluster_proxy_enable_dev_mode=$(jq -r 'if has("cluster_proxy_enable_dev_mode") then .cluster_proxy_enable_dev_mode else "true" end' "${json_file_path}")
cluster_proxy_auth0_audience=$(jq -r '.cluster_proxy_auth0_audience // "dev-proxy-service"' "${json_file_path}")
cluster_proxy_auth0_domain=$(jq -r '.cluster_proxy_auth0_domain // "tidb-dev.us.auth0.com"' "${json_file_path}")
full_manage_hosted_zone_domain=$(jq -r '.full_manage_hosted_zone_domain // "clusters.dev.tidb-cloud.com"' "${json_file_path}")
full_manage_hosted_zone_id=$(jq -r '.full_manage_hosted_zone_id // "Z001609810TV4E79YOP22"' "${json_file_path}")
full_manage_hosted_zone_resource_group=$(jq -r '.full_manage_hosted_zone_resource_group // "dev-eastus-controlplane"' "${json_file_path}")
full_manage_pca_arn=$(jq -r '.full_manage_pca_arn // "arn:aws:acm-pca:us-west-2:385595570414:certificate-authority/4668d5cc-1042-4371-9ff4-72ab9493c545"' "${json_file_path}")
crossplane_azure_tenant_id=$(jq -r '.crossplane_azure_tenant_id // ""' "${json_file_path}")
crossplane_azure_subscription_id=$(jq -r '.crossplane_azure_subscription_id // ""' "${json_file_path}")
crossplane_azure_client_id=$(jq -r '.crossplane_azure_client_id // ""' "${json_file_path}")
azure_workload_identity_client_id=$(jq -r '.azure_workload_identity_client_id // ""' "${json_file_path}")

# External Secretes
cluster_proxy_auth0_secret_key=$(jq -r '.cluster_proxy_auth0_secret_key // "dev-proxy-auth0-client"' "${json_file_path}")
o11y_auth0_secret_key=$(jq -r '.o11y_auth0_secret // "dev-o11y-auth0-client"' "${json_file_path}")
config_manager_auth_key=$(jq -r '.config_manager_auth_key // "dev-config-manager-account-xregion-auth-key"' "${json_file_path}")
config_manager_clinic_activity_key=$(jq -r '.config_manager_clinic_activity_key // "dev-config-manager-clinic-activity-key"' "${json_file_path}")

gcp_service_account=$(jq -r '.gcp_service_account // ""' "${json_file_path}")
gcp_cluster_server_service_account=$(jq -r '.gcp_cluster_server_service_account // ""' "${json_file_path}")
if [[ "$cloud" == gcp ]]; then
  [[ "$gcp_service_account" == *@*.iam.gserviceaccount.com ]] || { echo "gcp_service_account is required" >&2; exit 1; }
  # Legacy non-Terraform callers use the historical env-cluster-server name.
  gcp_cluster_server_service_account=${gcp_cluster_server_service_account:-${env}-cluster-server}
  gcp_controlplane_project=${gcp_service_account#*@}
  gcp_controlplane_project=${gcp_controlplane_project%.iam.gserviceaccount.com}
  gcp_cluster_server_sa=${gcp_cluster_server_service_account%%@*}
fi

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

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

echo "Prepare manifest files"
if [[ "$cloud" == gcp ]]; then
  for patch in replicas resources toleration; do
    cp "${variant_dir}/${patch}_tmpl.yaml" "${deploy_dir}/${patch}.yaml"
  done
fi
cp "${variant_dir}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"
cp "${variant_dir}/version_tmpl.yaml" "${deploy_dir}/version.yaml"
cp "${variant_dir}/root-config_tmpl.yaml" "${deploy_dir}/root-config.yaml"
cp "${variant_dir}/args_tmpl.yaml" "${deploy_dir}/args.yaml"
cp "${variant_dir}/serviceaccount_tmpl.yaml" "${deploy_dir}/serviceaccount.yaml"
[ -f "${variant_dir}/providerconfig_tmpl.yaml" ] && cp "${variant_dir}/providerconfig_tmpl.yaml" "${deploy_dir}/providerconfig.yaml"
[ -f "${variant_dir}/self-signed-ca-secret_tmpl.yaml" ] && cp "${variant_dir}/self-signed-ca-secret_tmpl.yaml" "${deploy_dir}/self-signed-ca-secret.yaml"
cp "${variant_dir}/secrets_tmpl.yaml" "${deploy_dir}/secrets.yaml"

# https://stackoverflow.com/questions/4247068/sed-command-with-i-option-failing-on-mac-but-works-on-linux
if [[ "$OSTYPE" == "darwin"* ]]; then
  # Require gnu-sed.
  if ! [ -x "$(command -v gsed)" ]; then
    echo "Error: 'gsed' is not istalled." >&2
    echo "If you are using Homebrew, install with 'brew install gnu-sed'." >&2
    exit 1
  fi
  SED_CMD=gsed
else
  SED_CMD=sed
fi

${SED_CMD} -i "s|REGION|${region}|g" "${deploy_dir}/args.yaml"
${SED_CMD} -i "s|READONLY_ASSUME_ROLE_NAME|${readonly_assume_role_name}|g" "${deploy_dir}/args.yaml"
${SED_CMD} -i "s|ASSUME_ROLE_NAME|${assume_role_name}|g" "${deploy_dir}/args.yaml"
${SED_CMD} -i "s|CLUSTER_SERVER_ROLE_ARN|${aws_cluster_server_role_arn}|g" "${deploy_dir}/args.yaml"
${SED_CMD} -i "s|IRSA_ROLE_ARN|${irsa_role_arn}|g" "${deploy_dir}/serviceaccount.yaml"
${SED_CMD} -i "s|AZURE_WORKLOAD_IDENTITY_CLIENT_ID|${azure_workload_identity_client_id}|g" "${deploy_dir}/serviceaccount.yaml"
[ -f "${deploy_dir}/providerconfig.yaml" ] && ${SED_CMD} -i "s|GLOBAL_ROLE_ARN|${global_role_arn}|g" "${deploy_dir}/providerconfig.yaml"
${SED_CMD} -i "s|IMAGE_REGISTRY|${image_registry}|g" "${deploy_dir}/args.yaml"
${SED_CMD} -i "s|IMAGE_REGISTRY|${image_registry}|g" "${deploy_dir}/version.yaml"

${SED_CMD} -i "s|PROXY_AUTH0_SECRET_KEY|${cluster_proxy_auth0_secret_key}|g" "${deploy_dir}/secrets.yaml"
${SED_CMD} -i "s|O11Y_AUTH0_SECRET_KEY|${o11y_auth0_secret_key}|g" "${deploy_dir}/secrets.yaml"
${SED_CMD} -i "s|CONFIG_MANAGER_AUTH_KEY|${config_manager_auth_key}|g" "${deploy_dir}/secrets.yaml"
${SED_CMD} -i "s|CONFIG_MANAGER_CLINIC_ACTIVITY_KEY|${config_manager_clinic_activity_key}|g" "${deploy_dir}/secrets.yaml"
[ -f "${variant_dir}/self-signed-ca-secret.yaml" ] && ${SED_CMD} -i "s|SELF_SIGNED_CA_KEY|${self_signed_ca_key}|g" "${deploy_dir}/self-signed-ca-secret.yaml"

${SED_CMD} -i "s|REGION|${region}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|IMAGE_REGISTRY|${image_registry}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CONFIG_CHANGE_ENV|${config_change_env}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CONFIG_CHANGE_ACTIVITY_ENABLED|${config_change_activity_enabled}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CONFIG_CHANGE_ACTIVITY_HUB_EP|${config_change_activity_hub_ep}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CONFIG_CHANGE_ACTIVITY_SOURCE_NAME|${config_change_activity_source}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CONFIG_CHANGE_CLINIC_EP|${config_change_activity_clinic_ep}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|PROXY_ENABLE_DEV_MODE|${cluster_proxy_enable_dev_mode}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|PROXY_AUTH0_AUDIENCE|${cluster_proxy_auth0_audience}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|PROXY_AUTH0_DOMAIN|${cluster_proxy_auth0_domain}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|FULL_MANAGE_HOSTED_ZONE_DOMAIN|${full_manage_hosted_zone_domain}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|FULL_MANAGE_HOSTED_ZONE_ID|${full_manage_hosted_zone_id}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|FULL_MANAGE_HOSTED_ZONE_RESOURCE_GROUP|${full_manage_hosted_zone_resource_group}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|FULL_MANAGE_PCA_ARN|${full_manage_pca_arn}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CROSSPLANE_AZURE_TENANT_ID|${crossplane_azure_tenant_id}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CROSSPLANE_AZURE_SUBSCRIPTION_ID|${crossplane_azure_subscription_id}|g" "${deploy_dir}/root-config.yaml"
${SED_CMD} -i "s|CROSSPLANE_AZURE_CLIENT_ID|${crossplane_azure_client_id}|g" "${deploy_dir}/root-config.yaml"

if [[ "$cloud" == gcp ]]; then
  ${SED_CMD} -i "s|GCP_SERVICE_ACCOUNT_PLACEHOLDER|${gcp_service_account}|g" "${deploy_dir}/serviceaccount.yaml"
  ${SED_CMD} -i "s|GCP_CONTROLPLANE_PROJECT_PLACEHOLDER|${gcp_controlplane_project}|g" "${deploy_dir}/root-config.yaml" "${deploy_dir}/providerconfig.yaml"
  ${SED_CMD} -i "s|GCP_CLUSTER_SERVER_SA_PLACEHOLDER|${gcp_cluster_server_sa}|g" "${deploy_dir}/root-config.yaml"
fi
