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


additional_args=$(jq -r '.' "${args_file_path}")
echo "additional_args: ${additional_args}"
crossplane_aws_role_arn=$(echo ${additional_args} | jq -r '.crossplaneAwsRoleArn')

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 "${deploy_dir}"
echo "Prepare manifest files"
cp "${variant_dir}/deploymentruntimeconfig-aws-family_tmpl.yaml" "${deploy_dir}/deploymentruntimeconfig-aws-family.yaml"
cp "${variant_dir}/kustomization_tmpl.yaml" "${deploy_dir}/kustomization.yaml"

if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    SED_IN_PLACE=(-i '')
else
    # Linux and others
    SED_IN_PLACE=(-i)
fi

find "${deploy_dir}" -type f -exec sed "${SED_IN_PLACE[@]}" "s|TMPL_CROSSPLANE_AWS_ROLE_ARN|${crossplane_aws_role_arn}|g" {} \;
