#!/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 == "alicloud" ]]; then
  vswitch_ids_string=$(echo ${args} | jq -r '.vswitchIDs')
  hosted_zone_name=$(echo ${args} | jq -r '.hostedZoneName')
  image_registry=$(echo ${args} | jq -r '.imageRegistry')

  deploy_dir="${ROOT}/envs/${env}-${vendor}-${logical_region}"
  deploy_alb_file="${deploy_dir}/albconfig.yaml"
  deploy_read_controller_file="${deploy_dir}/values.yaml"
  deploy_read_ingress_file="${deploy_dir}/ingress.yaml"
  deploy_private_key_file="${deploy_dir}/privatekey.yaml"
  variant_dir="${ROOT}/variants"
  alicloud_vswmap=""
  IFS=',' read -r -a vswitch_ids <<<"$vswitch_ids_string"
  for id in "${vswitch_ids[@]}"; do
    alicloud_vswmap+="    - vSwitchId: $id\\n"
  done
  alicloud_vswmap=${alicloud_vswmap%\\n}
  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}/alicloud/alicloud-albconfig-tmpl.yaml" "${deploy_alb_file}"
    cp "${variant_dir}/alicloud/${env}-alicloud-values-tmpl.yaml" "${deploy_read_controller_file}"
    cp "${variant_dir}/alicloud/${env}-${vendor}-ingress-tmpl.yaml" "${deploy_read_ingress_file}"
    cp "${variant_dir}/alicloud/alicloud-privatekey-tmpl.yaml" "${deploy_private_key_file}"

    echo "Generating self-signed TLS certificate for *.${hosted_zone_name}"
    openssl req -x509 -newkey rsa:4096 -nodes -days 3650 \
      -keyout albtop-key.pem -out albtop-cert.pem \
      -subj "/CN=*.${hosted_zone_name}" \
      -addext "subjectAltName=DNS:*.${hosted_zone_name},DNS:${hosted_zone_name}"
    tls_key=$(base64 -w0 albtop-key.pem 2>/dev/null || base64 -i albtop-key.pem)
    tls_cert=$(base64 -w0 albtop-cert.pem 2>/dev/null || base64 -i albtop-cert.pem)
    rm albtop-key.pem albtop-cert.pem

    if [[ "$(uname)" == "Darwin" ]]; then
      # macOS
      sed -i '' "s|TMPL_ZONES|${alicloud_vswmap}|g" ${deploy_alb_file}
      sed -i '' "s|TMPL_HOSTED_ZONE_NAME|${hosted_zone_name}|g" ${deploy_read_ingress_file}
      sed -i '' "s|TMPL_REGION|${region}|g" ${deploy_read_ingress_file}
      sed -i '' "s|TMPL_LOGICAL_REGION|${logical_region}|g" ${deploy_read_ingress_file}
      sed -i '' "s|TMPL_TLS_KEY|${tls_key}|g" ${deploy_private_key_file}
      sed -i '' "s|TMPL_TLS_CERT|${tls_cert}|g" ${deploy_private_key_file}
      sed -i '' "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" ${deploy_read_controller_file}
    else
      # Linux
      sed -i "s|TMPL_ZONES|${alicloud_vswmap}|g" ${deploy_alb_file}
      sed -i "s|TMPL_HOSTED_ZONE_NAME|${hosted_zone_name}|g" ${deploy_read_ingress_file}
      sed -i "s|TMPL_REGION|${region}|g" ${deploy_read_ingress_file}
      sed -i "s|TMPL_LOGICAL_REGION|${logical_region}|g" ${deploy_read_ingress_file}
      sed -i "s|TMPL_TLS_KEY|${tls_key}|g" ${deploy_private_key_file}
      sed -i "s|TMPL_TLS_CERT|${tls_cert}|g" ${deploy_private_key_file}
      sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" ${deploy_read_controller_file}
    fi
  fi
fi

if [[ $vendor != "alicloud" ]]; then
  hosted_zone_name=$(echo ${args} | jq -r '.hostedZoneName // ""')
  ds_waf_id=$(echo ${args} | jq -r '.dsWAFID')
  cert_arn=$(echo ${args} | jq -r '.dsCertID')
  accesss_log_bucket=$(echo ${args} | jq -r '.dsLogsBucketName')
  image_registry=$(echo ${args} | jq -r '.imageRegistry')
  byoc=$(echo ${args} | jq -r '.byoc // "false"')

  deploy_dir="${ROOT}/envs/${env}-${vendor}-${logical_region}"
  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"
    if [[ ${byoc} == "true" ]]; then
        byoc_values_tmpl="${variant_dir}/${vendor}/byoc-${env}-${vendor}-values-tmpl.yaml"
        if [[ "${vendor}" == "azure" ]]; then
            if [[ ! -f "${byoc_values_tmpl}" ]]; then
                echo "Error: Azure BYOC ingress-nginx-read values template not found for env ${env}: ${byoc_values_tmpl}" >&2
                exit 1
            fi
            cp "${byoc_values_tmpl}" "${deploy_dir}/values.yaml"
        else
            if [[ ! -f "${byoc_values_tmpl}" ]]; then
                byoc_values_tmpl="${variant_dir}/${vendor}/byoc-${vendor}-values-tmpl.yaml"
            fi
            cp "${byoc_values_tmpl}" "${deploy_dir}/values.yaml"
            if [ -f "${variant_dir}/${vendor}/byoc-${vendor}-ingress-tmpl.yaml" ]; then
                cp "${variant_dir}/${vendor}/byoc-${vendor}-ingress-tmpl.yaml" "${deploy_dir}/ingress.yaml"
            else
                cp "${variant_dir}/${vendor}/${vendor}-ingress-tmpl.yaml" "${deploy_dir}/ingress.yaml"
            fi
        fi
    else
        cp "${variant_dir}/${vendor}/${env}-${vendor}-values-tmpl.yaml" "${deploy_dir}/values.yaml"
        cp "${variant_dir}/${vendor}/${vendor}-ingress-tmpl.yaml" "${deploy_dir}/ingress.yaml"
    fi

    find "${deploy_dir}" -type f -print0 | while IFS= read -r -d '' file; do
      replace_token "TMPL_LOGICAL_REGION" "${logical_region}" "${file}"
      replace_token "TMPL_REGION" "${region}" "${file}"
      replace_token "TMPL_HOSTED_ZONE_NAME" "${hosted_zone_name}" "${file}"
      replace_token "TMPL_DS_WAF_ID" "${ds_waf_id}" "${file}"
      replace_token "TMPL_ACCESS_LOG_BUCKET_NAME" "${accesss_log_bucket}" "${file}"
      replace_token "TMPL_IMAGE_REGISTRY" "${image_registry}" "${file}"
      replace_token "TMPL_CERTIFICATE_ARN" "${cert_arn}" "${file}"
    done
  fi
fi
