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

vmcluster_bucket=$(echo ${args} | jq -r '.vmclusterBucketName')
vmcluster_role_arn=$(echo ${args} | jq -r '.vmclusterRoleARN')
nginx_read_ingress_class=$(echo ${args} | jq -r '.nginxReadIngressClass')
nginx_write_ingress_class=$(echo ${args} | jq -r '.nginxWriteIngressClass')
image_registry=$(echo ${args} | jq -r '.imageRegistry')
storage_account_name=$(echo ${args} | jq -r '.storageAccountName')
byoc=$(echo ${args} | jq -r '.byoc // "false"')

# Construct alicloud OSS internal endpoint from region
custom_s3_endpoint="http://oss-${region}-internal.aliyuncs.com"

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

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

	if [[ "${byoc}" == "true" ]]; then
		deploy_file="${deploy_dir}/values.yaml"
		cp "${variant_dir}/${env}-${vendor}-byoc-values-tmpl.yaml" "${deploy_file}"
	else
		deploy_file="${deploy_dir}/values.yaml"
		cp "${variant_dir}/${env}-${vendor}-values-tmpl.yaml" "${deploy_file}"
	fi

  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_REGION|${region}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_VENDOR|${vendor}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_VMCLUSTER_BUCKET_NAME|${vmcluster_bucket}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_STORAGE_ACCOUNT_NAME|${storage_account_name}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_VMCLUSTER_ROLE|${vmcluster_role_arn}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_NGINX_READ_INGRESS_CLASS|${nginx_read_ingress_class}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_NGINX_WRITE_INGRESS_CLASS|${nginx_write_ingress_class}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_IMAGE_REGISTRY|${image_registry}|g" {} \;
  find "${deploy_dir}" -type f -exec sed -i "s|TMPL_CUSTOM_S3_ENDPOINT|${custom_s3_endpoint}|g" {} \;
fi
