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

if [[ "$vendor" == "azure" ]]; then
    azure_client_id=$(echo ${args} | jq -r '.azureClientID')
fi

if [[ "$vendor" == "alicloud" ]]; then
  image_registry=$(echo ${args} | jq -r '.imageRegistry')
fi

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

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 log stats 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}"
  if [[ "$vendor" == "alicloud" ]]; then
    sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" "${deploy_file}"
  fi
  if [[ "$vendor" == "azure" ]]; then
    sed -i "s|TMPL_AZURE_CLIENT_ID|${azure_client_id}|g" "${deploy_file}"
  fi
fi
