#!/usr/bin/env bash
set -euo pipefail
# When changing this script, remember to modify the corresponding github action
region=${1}
env=${2}
cloud=${3}
json_file_path=${4}
logicalRegionName=${5}

additional_args=$(jq -r '.' "${json_file_path}")

echo "additional_args: ${additional_args}"

image_registry=$(echo ${additional_args} | jq -r '.imageRegistry')
plugins=$(echo ${additional_args} | jq -r '.plugins')
zone_maps=$(echo ${additional_args} | jq -r '.zoneMaps')

# Aliyun NLB workaround (issue #16): drop the dynamic
# globalControlplaneIPs + regionalControlplaneIPs injection on alicloud only;
# AWS/Azure still rely on it. Gated so alicloud deploy JSONs (which don't
# carry these fields) don't fail at jq read time.
if [[ $cloud != "alicloud" ]]; then
  global_controlplane_ips=$(echo ${additional_args} | jq -r '.globalControlplaneIPs')
  regional_controlplane_ips=$(echo ${additional_args} | jq -r '.regionalControlplaneIPs')
fi

# Aliyun NLB workaround (issue #16): managed SGs can't be deleted, so we pass
# our own SG via the security-group-ids annotation. AWS/Azure templates don't
# carry the SECURITY_GROUP_IDS placeholder at all, so this gate is also what
# stops them from being rejected by the fail-fast below — `jq -r` on a
# missing field returns the literal string "null" which `set -euo pipefail`
# does not catch.
if [[ $cloud == "alicloud" ]]; then
  security_group_ids=$(echo ${additional_args} | jq -r '.securityGroupIds')
  if [[ $security_group_ids == "null" || -z $security_group_ids ]]; then
    echo "ERROR: missing securityGroupIds in ${json_file_path}" >&2
    exit 1
  fi
fi

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

if [ -e ${deploy_dir} ]; then
  echo "New region deploy directory already exist"
  exit 1
fi

mkdir -p "${deploy_dir}"
echo "Prepare manifest files"
cp "${variant_dir}/values_tmpl.yaml" "${deploy_dir}/values.yaml"


find "${deploy_dir}" -type f -exec sed -i "s|TMPL_REGION|${region}|g" {} \;
sed -i "s|IMAGE_REGISTRY|${image_registry}|g" "${deploy_dir}/values.yaml"
sed -i "s|ZONE_MAPS|${zone_maps}|g" "${deploy_dir}/values.yaml"

if [[ $cloud == "alicloud" ]]; then
  sed -i "s|SECURITY_GROUP_IDS|${security_group_ids}|g" "${deploy_dir}/values.yaml"
fi

# Aliyun NLB workaround (issue #16): skip the dynamic source-range injection
# on alicloud — the controller would otherwise auto-create a managed SG.
if [[ $cloud != "alicloud" ]]; then
  yq e -i ".proxy.loadBalancerSourceRanges |= ${global_controlplane_ips} + ${regional_controlplane_ips}" ${deploy_dir}/values.yaml
fi

if [[ $plugins != "null" ]]; then
  yq e -i ". += {\"plugins\": $plugins}" ${deploy_dir}/values.yaml
fi
