#!/usr/bin/env bash
set -euo pipefail
# When changing this script, remember to modify the corresponding github action
region=${1}
env=${2}
cloud=${3}
role_arn=${4}
logicalRegionName=${5}
gcp_service_account=${6:-}
gcp_project=${7:-}
# Actual GKE cluster name, which can differ from the ArgoCD destination name.
gcp_cluster=${8:-}
if [[ "$cloud" == gcp ]]; then
  [[ "$gcp_service_account" == *@*.iam.gserviceaccount.com && -n "$gcp_project" && -n "$gcp_cluster" ]] || { echo "gcpServiceAccount, gcpSecretManagerProject and gcpClusterName (actual GKE cluster name) are required" >&2; exit 1; }
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}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"
cp "${variant_dir}/secretstore_tmpl.yaml" "${deploy_dir}/secretstore.yaml"
cp "${variant_dir}/serviceaccount_tmpl.yaml" "${deploy_dir}/serviceaccount.yaml"

sed -i.bak "s|REGION|${region}|g" "${deploy_dir}/secretstore.yaml"
sed -i.bak "s|ROLE_ARN|${role_arn}|g" "${deploy_dir}/serviceaccount.yaml"

if [[ "$cloud" == gcp ]]; then
  sed -i.bak "s|GCP_SERVICE_ACCOUNT_PLACEHOLDER|${gcp_service_account}|g" "${deploy_dir}/serviceaccount.yaml"
  gcp_cluster_project=${gcp_service_account#*@}
  gcp_cluster_project=${gcp_cluster_project%.iam.gserviceaccount.com}
  sed -i.bak "s|GCP_CLUSTER_PROJECT_PLACEHOLDER|${gcp_cluster_project}|g; s|GCP_CLUSTER_LOCATION_PLACEHOLDER|${region}|g; s|GCP_CLUSTER_NAME_PLACEHOLDER|${gcp_cluster}|g" "${deploy_dir}/secretstore.yaml"
  sed -i.bak "s|GCP_PROJECT_PLACEHOLDER|${gcp_project}|g" "${deploy_dir}/secretstore.yaml"
fi
rm -f "${deploy_dir}/secretstore.yaml.bak" "${deploy_dir}/serviceaccount.yaml.bak"
