#!/usr/bin/env bash

set -euo pipefail

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source "${ROOT}/lib.sh"

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

o11y_repo=tidbcloud/observability
git_ref="main"
env=$(yq '.env' "${local_config}")
logical_region_name=$(yq '.name' "${local_config}")

echo "env: $env"
echo "logical_region_name: $logical_region_name"

# Create/update the o11y agent-writer IAM roles (trust policies included) for
# this logical region before the regional server is deployed.
gh workflow run o11y-static-principal-access.yaml --repo ${o11y_repo} --ref ${git_ref} \
  -f git-ref=${git_ref} \
  -f env=${env} \
  -f vendor=aws \
  -f logical-region=${logical_region_name} \
  -f dry-run=false

wait_workflow_run_to_merge o11y-static-principal-access.yaml ${o11y_repo}
if [[ $? -eq 1 ]]; then
    exit 1
fi
