#!/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')
storage_account_name=$(echo ${args} | jq -r '.storageAccountName // ""')
bucket_name=$(echo ${args} | jq -r '.bucketName // .diagBucketName // ""')

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 query already exist, skip it"
    else
      mkdir -p ${deploy_dir}
      echo "Prepare manifest files"

      cp "${variant_dir}/values-tmpl.yaml" "${deploy_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_STORAGE_ACCOUNT_NAME|${storage_account_name}|g" "${deploy_file}"
      sed -i "s|TMPL_BUCKET_NAME|${bucket_name}|g" "${deploy_file}"
    fi
fi
