#!/usr/bin/env bash
set -xeuo pipefail

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

remote_config=${CONFIG_PATH}
local_config=/tmp/config.yaml
download_blob "${remote_config}" "${local_config}"

argocd_repo=tidbcloud/app-delivery
region=$(yq '.region' "${local_config}")
logicalRegionName=$(yq '.name' "${local_config}")
env=$(yq '.env' "${local_config}")
cloud=$(yq '.cloudProvider' "${local_config}")
cluster=$(yq '.k8s.name' "${local_config}")
jobId=$(yq '.jobId' "${local_config}")
imageRegistry=$(yq '.imageRegistry' "${local_config}")

additionalArgs=$(cat <<EOF
{
  "imageRegistry": "$imageRegistry"
}
EOF
)
echo "additionalArgs: $additionalArgs"

# Deploy application services by invoking deploy-new-region action in $argocd_repo
common_params="-f cloud=${cloud} -f region=${region} -f env=${env} -f cluster=${cluster} -f jobId=${jobId} -f logicalRegionName=${logicalRegionName}"
export GH_REPO="${argocd_repo}"
gh workflow run deploy-new-region-victoria-metrics-operator.yaml ${common_params} -f additionalArgs="${additionalArgs}"

# Wait services ready
declare -A services
services["deploy/o11ystack-seed-victoria-metrics-operator"]="false"
ns="monitoring"
wait_for_services_ready services ns
if [[ $? -eq 1 ]]; then
    echo "Services are not ready"
    exit 1
fi
