#!/bin/bash
set -euo pipefail

env=$1
name=$2
region=$3
output_uri=$4
tf_s3_bucket=$5
advance_options=$6
preview=$7

action="apply -auto-approve"
if [[ "$preview" == "true" ]]; then
  action="plan"
fi

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
tf_directory="${ROOT}/aws"
tf_s3_region=$(aws s3api get-bucket-location --bucket=$tf_s3_bucket --region=$region --query="LocationConstraint" --output=text --no-cli-pager)
tf_state="region-shared-resoruces/ng-rds/${env}-${region}-${name}.json"
cd "${tf_directory}"
terraform init -reconfigure -backend-config="bucket=${tf_s3_bucket}" -backend-config="key=${tf_state}" -backend-config="region=${tf_s3_region}"
terraform $action \
  -var="env=${env}" \
  -var="name=${name}" \
  -var="region=${region}" \
  -var-file="${advance_options}"

if [[ "$preview" == "true" ]]; then
  echo "Preview completed. No changes applied."
  exit 0
fi

local_output="/tmp/ng-rds-output.yaml"
bucket_name=${output_uri#s3://}
bucket_name=${bucket_name%%/*}
output_bucket_region=$(aws s3api get-bucket-location --bucket=$bucket_name --region=$region --query="LocationConstraint" --output=text --no-cli-pager)

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}" "${output_uri}" --region=$output_bucket_region
