#!/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"
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}")
byoc_tenant_id=$(yq '.jobOptions.o11yRegion.byocTenantID // "" ' "${local_config}")

o11y_eks_remote_output=$(yq '.jobOutput.o11y-eks' "${local_config}")
o11y_eks_local_output=/tmp/o11y-eks-output.yaml
aws s3 cp ${o11y_eks_remote_output} ${o11y_eks_local_output}  --region=$output_bucket_region
cluster=$(yq '.cluster_name' "${o11y_eks_local_output}")

account_id=$(yq -r -ojson '.aws.dataplaneAccounts.0' "${local_config}")

# Get API Gateway endpoint
api_name="o11y-${env}-${logical_region_name}"
echo "Querying API Gateway: $api_name"
api_id=$(aws --profile $account_id apigateway get-rest-apis \
  --region $region \
  --query "items[?name=='$api_name'].id" \
  --output text 2>/dev/null || echo "")

if [ -z "$api_id" ] || [ "$api_id" == "None" ]; then
  echo "Error: API Gateway not found: $api_name"
  exit 1
fi

api_endpoint="https://${api_id}.execute-api.${region}.amazonaws.com/tidbcloud"
echo "API Gateway endpoint: $api_endpoint"

# Construct addresses from API Gateway endpoint
ds_address="${api_endpoint}/ds"
rs_address="${api_endpoint}/rs"

# Get access principal for cross-account access
# The access principal is the IAM role ARN that will be allowed to invoke the API Gateway
# Use fixed role name "tidbcloud-o11y-apigw-role" in the dataplane account
access_principal="arn:aws:iam::${account_id}:role/tidbcloud-o11y-apigw-role"

# External ID is empty for this use case now
access_external_id=""

args=$(cat <<EOF
{
  "rsAddress": "$rs_address",
  "dsAddress": "$ds_address",
  "tenantID": "$byoc_tenant_id",
	"accessPrincipal": "$access_principal",
	"accessExternalID": "$access_external_id"
}
EOF
)
echo "args: $args"

common_params="-f vendor=${vendor} -f region=${region} -f logicalRegionName=${logical_region_name} -f env=${env} -f cluster=${cluster} -f jobId=${jobId}"

# Create pull request by invoking new-region workflow.
gh workflow run new-region-global.yaml --repo ${o11y_repo} --ref ${git_ref} ${common_params} -f args="${args}"
wait_workflow_run_to_merge new-region-global.yaml ${o11y_repo}
if [[ $? -eq 1 ]]; then
    exit 1
fi

# deploy globalserver
echo "start triggering globalserver-cd to deploy global-server"
gh workflow run global-server-cd.yaml --repo ${o11y_repo} --ref ${git_ref} -f git-ref=${git_ref} -f env=${env}
wait_workflow_success global-server-cd.yaml ${o11y_repo}
if [[ $? -eq 1 ]]; then
  echo "Workflow failed"
  exit 1
fi

# deploy infra
echo "start triggeering infra-cd to deploy global infra"
gh workflow run infra-cd-v2.yaml --repo ${o11y_repo} --ref ${git_ref} -f git-ref=${git_ref} -f vendor=global -f region=us-west-2 -f env=${env}
wait_workflow_success infra-cd-v2.yaml ${o11y_repo}
if [[ $? -eq 1 ]]; then
  echo "Workflow failed"
  exit 1
fi

