#!/usr/bin/env bash
set -xeuo pipefail
# This script should be idempotent and retriable
# It's used to deploy a new region
# When adding a new dataplane aws account, this script should be
# invoked several times, each with a single region
remote_config=${CONFIG_PATH}
local_config=/tmp/base-config.yaml

bucket_name=${remote_config#s3://}
bucket_name=${bucket_name%%/*}
output_bucket_region=$(aws s3api get-bucket-location --bucket=$bucket_name --query="LocationConstraint" \
  --region=us-west-2 --output=text --no-cli-pager)
aws s3 cp "${remote_config}" "${local_config}" --region=$output_bucket_region

env=$(yq '.env' "${local_config}")
region=$(yq '.region' "${local_config}")
dataplane_accounts=$(yq -ojson '.aws.dataplaneAccounts' "${local_config}" | jq -r '.[]')

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
tf_directory="${ROOT}/terraform"
tf_s3_bucket=$(yq '.terraformStateBucket' "${local_config}")
tf_s3_region=$(aws s3api get-bucket-location --bucket $tf_s3_bucket --region $region --query "LocationConstraint" --output text)

module_path="service-quota"
cd "${tf_directory}/${module_path}"
for acct in ${dataplane_accounts[@]}; do
  tf_state="${module_path}/${acct}-${env}-${region}-tfstate.json"
  terraform init -backend-config="bucket=${tf_s3_bucket}" -backend-config="key=${tf_state}" -backend-config="region=${tf_s3_region}"
  sleep 300 && terraform apply -auto-approve -var="account=${acct}" -var="region=${region}"
done