#!/usr/bin/env bash

set -euo pipefail

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

app_repo=tidbcloud/app-delivery
git_ref="main"
region=$(yq '.region' "${local_config}")
logical_region_name=$(yq '.name' "${local_config}")
env=$(yq '.env' "${local_config}")
vendor=$(yq '.cloudProvider' "${local_config}")
jobId=$(yq '.jobId' "${local_config}")

clinic_env=$env
if [[ $env == "prod" ]]; then
    clinic_env="dev,staging,prod"
fi
datasource_name="Loki-${vendor}-${logical_region_name}"
params="-f env="$clinic_env" -f name="${datasource_name}" -f jobId=${jobId}"

# Create pull request by invoking new-region workflow.
gh workflow run remove-loki-datasource.yaml --repo ${app_repo} --ref ${git_ref} ${params}
