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

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

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

mkdir -p "${deploy_dir}"
echo "Prepare manifest files"
if [ "${cloud}" == "aws" ]; then
  cp "${variant_dir}/serviceaccount_tmpl.yaml" "${deploy_dir}/serviceaccount.yaml"
fi
if [ "${cloud}" == "alicloud" ] || [ "${cloud}" == "azure" ]; then
  cp "${variant_dir}/deploymentruntimeconfig-aws-family_tmpl.yaml" "${deploy_dir}/deploymentruntimeconfig-aws-family.yaml"
fi
cp "${variant_dir}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"

if [[ "$OSTYPE" == "darwin"* ]]; then
  # Require gnu-sed.
  if ! [ -x "$(command -v gsed)" ]; then
    echo "Error: 'gsed' is not istalled." >&2
    echo "If you are using Homebrew, install with 'brew install gnu-sed'." >&2
    exit 1
  fi
  SED_CMD=gsed
else
  SED_CMD=sed
fi

find "${deploy_dir}" -type f -exec ${SED_CMD} -i "s|TMPL_IRSA_ROLE_ARN|${irsa_role_arn}|g" {} \;
