#!/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

cloud=$(yq '.cloudProvider' "${local_config}")
env=$(yq '.env' "${local_config}")
region=$(yq '.region' "${local_config}")
logicalRegionName=$(yq '.name' "${local_config}")
controlplane_account=$(yq '.aws.controlplaneAccount' "${local_config}")
dataplane_account=$(yq '.aws.dataplaneAccounts.0' "${local_config}")
job_id=$(yq '.jobId' "${local_config}")

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)

# Provision crossplane iam role in controlplane account
module_path="o11y-eks"
cd "${tf_directory}/${module_path}"
tf_state="${module_path}/${dataplane_account}-${env}-${logicalRegionName}-tfstate.json"
o11y_eks_options="${tf_directory}/o11y-eks-options.json"
yq -ojson '.jobOptions.o11yEksOptions' "${local_config}" > "${o11y_eks_options}"
terraform init -backend-config="bucket=${tf_s3_bucket}" -backend-config="key=${tf_state}" -backend-config="region=${tf_s3_region}"
terraform apply -auto-approve \
  -var="env=${env}" \
  -var="logical_region_name=${logicalRegionName}" \
  -var="region=${region}" \
  -var="account=${dataplane_account}" \
  -var-file=${o11y_eks_options}

remote_output=$(yq '.outputPath' "${local_config}")
local_output=/tmp/output.yaml
terraform output -json | yq 'with_entries({"key": .key, "value": .value.value})' -oyaml -P > "${local_output}"
echo "Write output to S3..."
aws s3 cp "${local_output}" "${remote_output}" --region=$output_bucket_region