#!/usr/bin/env bash
set -x

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

prefix=${1:-seed}
remote_config=${CONFIG_PATH}
local_config=/tmp/base-config.yaml
download_blob "${remote_config}" "${local_config}"

argocd_repo=tidbcloud/app-delivery
region=$(yq '.region' "${local_config}")
env=$(yq '.env' "${local_config}")
cloud=$(yq '.cloudProvider' "${local_config}")
cluster=$(yq '.k8s.name' "${local_config}")
jobId=$(yq '.jobId' "${local_config}")
output=$(yq '.outputPath' "${local_config}")
controlplaneTenantId=$(yq '.azure.controlplaneTenantId' "${local_config}")
controlplaneSubscriptionId=$(yq ".azure.controlplaneSubscriptionId" "${local_config}")

enableRegister=$(yq '.jobOptions.jumpServer.enabled' "${local_config}")
if [[ $enableRegister == "null" || $enableRegister == "false" ]]; then
  echo "Disable to register jump server destination"
  exit 0
fi

regionName=$(yq '.name' "${local_config}")
k8sEndpoint=$(yq '.k8s.endpoint' "${local_config}")
tenantId=$(yq ".jobOptions.jumpServer.tenantId // \"$controlplaneTenantId\"" "${local_config}")
subscriptionId=$(yq ".jobOptions.jumpServer.subscriptionId // \"$controlplaneSubscriptionId\"" "${local_config}")
clientId=$(yq '.jobOptions.jumpServer.clientId' "${local_config}")
jumpServerEnv=$(yq ".jobOptions.jumpServer.env // \"$env\"" "${local_config}")
tokenFilePath=$(yq '.jobOptions.jumpServer.tokenFilePath // "/var/run/secrets/federated-tokens/token-azure"' "${local_config}")

# support $env $region as part of prefix
prefix=$(eval "echo $prefix")
name="$prefix-${regionName}"
destination=$(cat <<EOF
type: controlplane
name: $name
k8sName: $cluster
k8sEndpoint: $k8sEndpoint
azureAuth:
  subscriptionID: $subscriptionId
  tenantID: $tenantId
  clientID: $clientId
  federatedTokenFilepath: $tokenFilePath
EOF
)

# Deploy application services by invoking deploy-new-region action in $argocd_repo
common_params="-f env=${jumpServerEnv} -f jobId=${jobId}"
export GH_REPO="${argocd_repo}"
gh workflow run new-jump-server-dst.yaml ${common_params} -f name="${name}" -f destination="${destination}"
