#!/usr/bin/env bash
set -xeo 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}")
output=$(yq '.outputPath' "${local_config}")
o11y_enabled=$(yq '.jobOptions.o11y.enabled' "${local_config}")

if [ "${o11y_enabled}" != "true" ]; then
  echo "o11y is not enabled, skipping o11y-agent finalizer"
  exit 0
fi

remote_o11y_agent_output=$(yq '.jobOutput.o11y-agent' "${local_config}")
local_o11y_agent_output=/tmp/o11y-agent-output.yaml
download_blob "${remote_o11y_agent_output}" "${local_o11y_agent_output}"
o11y_cluster_id=$(yq '.o11y_cluster_id' "${local_o11y_agent_output}")

# Destroy application services by invoking destroy-region-application action in $argocd_repo
common_params="--repo ${argocd_repo} -f cloud=${cloud} -f env=${env} -f logicalRegionName=${logicalRegionName} -f cluster=${cluster} -f jobId=${jobId}"
gh workflow run destroy-region-application.yaml ${common_params} -f application=o11y-agent

# Wait services to be removed
declare -A services
services["deploy/vmagent-${env}-seed-${logicalRegionName}-o11y"]="false"
services["vmagent/${env}-seed-${logicalRegionName}-o11y"]="false"
namespace=monitoring
wait_for_services_removed services namespace
if [[ $? -eq 1 ]]; then
  exit 1
fi

auth0_secret_id=$(yq '.jobOptions.o11y.auth0SecretID' "${local_config}")
# get keyvault name
remote_regional_resource_output=$(yq '.jobOutput.regional-resource' "${local_config}")
local_regional_resource_output=/tmp/regional-resource-output.yaml
download_blob "${remote_regional_resource_output}" "${local_regional_resource_output}"
keyvault_name=$(yq '.keyVault.name' "${local_regional_resource_output}")

deploy_tenant_id=$(yq '.azure.controlplaneTenantId' "${local_config}")
deploy_client_id=$(yq '.azure.controlplaneClientId' "${local_config}")
azureLogin $deploy_tenant_id $deploy_client_id

if az keyvault show --name ${keyvault_name} --resource-group ${cluster} > /dev/null 2>&1; then
  echo "Key Vault exists"
else
  echo "Key Vault has deleted, o11y-agent task must be successful"
  exit 0
fi

secret_string=$(az keyvault secret show --vault-name ${keyvault_name} --name ${auth0_secret_id} --query value -o tsv)
client_id=$(echo ${secret_string} | jq -r .Auth0ClientID)
client_secret=$(echo ${secret_string} | jq -r .Auth0ClientSecret)

o11y_global_endpoint=$(yq '.jobOptions.o11y.globalEndpoint' "${local_config}")
o11y_tenant_id=$(yq '.jobOptions.o11y.tenantId' "${local_config}")
o11y_project_id=$(yq '.jobOptions.o11y.projectId' "${local_config}")
o11y_rule_template_id=$(yq '.jobOptions.o11y.ruleTemplateId' "${local_config}")
seed_o11y_cluster_tag="auto-deploy-cli-created"

remote_iam_config=$(yq '.jobOutput.iam' "${local_config}")
local_iam_config=/tmp/iam-config.yaml
download_blob "${remote_iam_config}" "${local_iam_config}"
vector_role_arn=$(yq '.vector.roleArn' "${local_iam_config}")

echo "get auth0 token"
resp=$(
  curl -XPOST \
    --location 'https://tidb-soc2.us.auth0.com/oauth/token' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data-urlencode 'grant_type=client_credentials' \
    --data-urlencode "client_id=${client_id}" \
    --data-urlencode "client_secret=${client_secret}" \
    --data-urlencode 'audience=https://tidb-soc2.us.auth0.com/api/v2/'
)
access_token=$(echo "$resp" | jq -r '.access_token')
token="Bearer ${access_token}"

biz_type="${env}-tidbcloud"
if [ "$env" == "prod" ]; then
  biz_type="tidbcloud"
fi

echo "get o11y cluster info"
resp=$(
  curl -XGET -sL \
    --location "http://${o11y_global_endpoint}/api/v1/clusters/${o11y_cluster_id}?vendor=${cloud}&region=${region}" \
    --header "Authorization: ${token}" \
    --header "Content-Type: application/json"
)
code=$(echo -n "$resp" | jq -r '.code')
if [[ "$code" -ne 0 ]]; then
  if [[ "$code" == "20003" ]]; then
    echo "O11y cluster has not found (or deleted)"
    exit 0
  fi
  echo "Failed to get o11y cluster, code: $code"
  exit 1
fi

echo "check o11y cluster info"
cluster_info=$(echo "$resp" | jq ".data")
cluster_application_id=$(echo "$cluster_info" | jq -r ".applicationID")
cluster_biz_type=$(echo "$cluster_info" | jq -r ".bizType")
cluster_project_id=$(echo "$cluster_info" | jq -r ".projectID")
cluster_tenant_id=$(echo "$cluster_info" | jq -r ".tenantID")
cluster_vendor=$(echo "$cluster_info" | jq -r ".vendor")
cluster_template_id=$(echo "$cluster_info" | jq -r ".alertInfo.ruleTemplateID")
if [[ "$cluster_application_id" != "$logicalRegionName" ||
  "$cluster_biz_type" != "$biz_type" ||
  "$cluster_project_id" != "$o11y_project_id" ||
  "$cluster_template_id" != "$o11y_rule_template_id" ||
  "$cluster_tenant_id" != "$o11y_tenant_id" ]]; then
  echo "o11y cluster info is not matched, cluster info: $cluster_info"
  exit 1
fi

tags_count=$(echo "$cluster_info" | jq -r '.tags | length')
not_found="true"
for ((i=0; i<$tags_count; i++)); do
  tag=$(echo "$cluster_info" | jq -r ".tags[$i]")
  if [ "$tag" == "$seed_o11y_cluster_tag" ]; then
    not_found="false"
    break
  fi
done
if "$not_found"; then
  echo "o11y cluster $o11y_cluster_id is not created by auto deploy cli"
  exit 1
fi

echo "remove vpc endpoint"
endpoint_service_name=$(echo "$resp" | jq -r '.data.monitorInfo.endpointServiceName')
controlplane_subscription=$(yq '.azure.controlplaneSubscriptionId' "${local_config}")
vnet_name="$cluster-vnet"
subnet_name="$cluster-subnet"
o11y_endpoint_name="o11y-pe-$env-$logicalRegionName-controlplane"

az account set --subscription $controlplane_subscription
endpoint_id=$(az network private-endpoint show \
  -g $cluster \
  --name $o11y_endpoint_name | jq -r ".id")

if [ -n "$endpoint_id" ]; then
  echo "vpc endpoint ${endpoint_id} found, trying to remove"
  az  network private-endpoint delete --ids $endpoint_id
  while az network private-endpoint show --ids $endpoint_id 2>/dev/null; do
    echo "waiting for vpc endpoint to be removed..."
    sleep 5
  done
fi

echo "remove o11y cluster"
resp=$(
  curl -XDELETE -sL \
    --location "http://${o11y_global_endpoint}/api/v1/clusters/${o11y_cluster_id}?vendor=${cloud}&region=${region}" \
    --header "Authorization: ${token}" \
    --header "Content-Type: application/json"
)
code=$(echo -n "$resp" | jq -r '.code')
if [[ "$code" -ne 0 ]]; then
  echo "Failed to delete o11y cluster"
  exit 1
fi
