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

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

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}/serviceaccount_tmpl.yaml" "${deploy_dir}/serviceaccount.yaml"
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_RRSA_ROLE|${rrsa_role}|g" {} \;

echo "Generate externalsecret.yaml"
externalsecret_file="${deploy_dir}/dataplane-externalsecret.yaml"
# Start with an empty file
> "${externalsecret_file}"
for account_id in $(echo ${dataplane_account_ids} | jq -r '.[]'); do
  cat <<EOF >> "${externalsecret_file}"
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: dataplane-crossplane-provider-${account_id}
spec:
  refreshInterval: 1h
  secretStoreRef:
    kind: ClusterSecretStore
    name: default # name of the SecretStore (or kind specified)
  target:
    name: alibabacloud-dataplane-secret-${account_id} # name of the k8s Secret to be created
    creationPolicy: Owner
  dataFrom:
    - extract:
        key: crossplane-provider-${account_id}
---
EOF
done