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

image_registry=$(echo ${args} | jq -r '.imageRegistry')
account=$(echo ${args} | jq -r '.account // ""')
resource_group=$(echo ${args} | jq -r '.resourceGroup // ""')
storage_account_name=$(echo ${args} | jq -r '.storageAccountName // ""')
bucket_name=$(echo ${args} | jq -r '.bucketName // .diagBucketName // ""')

AZURE_DEFAULT_SUBSCRIPTION_ID="01f5d24b-a99c-45e1-a3e2-5ddc1e5bb71d"

if [[ "${vendor}" == "azure" && (-z "${account}" || "${account}" == "null") ]]; then
  account="${AZURE_DEFAULT_SUBSCRIPTION_ID}"
fi
if [[ -z "${resource_group}" || "${resource_group}" == "null" ]]; then
  resource_group="o11y-prod-regional-${region}"
fi
if [[ -z "${storage_account_name}" || "${storage_account_name}" == "null" ]]; then
  storage_account_name="o11yprod${region}"
fi
if [[ -z "${bucket_name}" || "${bucket_name}" == "null" ]]; then
  bucket_name="o11y-${env}-shared-${logical_region}"
fi

ROOT=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)

if [[ "$vendor" == "aws" || "$vendor" == "gcp" || "$vendor" == "alicloud" || "$vendor" == "azure" ]]; then
    deploy_dir="${ROOT}/envs/${env}-${vendor}-${logical_region}"
    deploy_file="${deploy_dir}/values.yaml"
    variant_dir="${ROOT}/variants/${vendor}"

    if [ -e ${deploy_dir} ]; then
      echo "New region deploy dir of diagnosis deltalake already exist, skip it"
    else
      mkdir -p ${deploy_dir}
      echo "Prepare manifest files"

      # First copy the template file
      cp "${variant_dir}/values-tmpl.yaml" "${deploy_file}"
      # Then perform replacements on the target file
      sed -i "s|TMPL_REGION|${region}|g" "${deploy_file}"
      sed -i "s|TMPL_ENV|${env}|g" "${deploy_file}"
      sed -i "s|TMPL_LOGICAL_REGION|${logical_region}|g" "${deploy_file}"
      sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" "${deploy_file}"
      sed -i "s|TMPL_ACCOUNT|${account}|g" "${deploy_file}"
      sed -i "s|TMPL_RESOURCE_GROUP|${resource_group}|g" "${deploy_file}"
      sed -i "s|TMPL_STORAGE_ACCOUNT_NAME|${storage_account_name}|g" "${deploy_file}"
      sed -i "s|TMPL_BUCKET_NAME|${bucket_name}|g" "${deploy_file}"
    fi
fi
