#!/usr/bin/env bash
set -xeo pipefail
o11y_agent_job_name=${1:-"o11y-agent"}

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

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_job_name}" "${local_config}")
local_o11y_agent_output=/tmp/o11y-agent-output.yaml
aws s3 cp ${remote_o11y_agent_output} ${local_o11y_agent_output} --region=$output_bucket_region
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=nextgen-o11y-agent

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

auth0_secret_id=$(yq '.jobOptions.secrets.o11yAuth0Secret' "${local_config}")
# read client secret using aws cli from aws secret manager
secret_string=$(aws secretsmanager get-secret-value --secret-id ${auth0_secret_id} --query SecretString --region us-west-2 --output text)
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
aws s3 cp ${remote_iam_config} ${local_iam_config} --region=$output_bucket_region
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-nextgen"

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 "X-Biz-Type: ${biz_type}" \
    --header "X-Org-Id: ${o11y_tenant_id}" \
    --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
  if [[ "$code" == "10003" ]]; then
    echo "O11y o11y regional server not found, cannot get o11y cluster info"
    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

endpoint_service_name=$(echo "$resp" | jq -r '.data.monitorInfo.endpointServiceName')
echo "get vpc"
vpc_id=$(aws eks describe-cluster \
  --name $cluster \
  --query "cluster.resourcesVpcConfig.vpcId" \
  --output text)
echo "found vpc: $vpc_id"

echo "remove vpc endpoint"
endpoint_id=$(aws ec2 describe-vpc-endpoints \
  --filters "Name=vpc-id,Values=$vpc_id" \
  --query "VpcEndpoints[?ServiceName=='$endpoint_service_name'].VpcEndpointId" \
  --output text)
if [ -n "$endpoint_id" ]; then
  echo "vpc endpoint ${endpoint_id} found, trying to remove"
  aws ec2 delete-vpc-endpoints --vpc-endpoint-ids $endpoint_id
  while aws ec2 describe-vpc-endpoints --vpc-endpoint-ids $endpoint_id 2>/dev/null; do
    echo "waiting for vpc endpoint to be removed..."
    sleep 5
  done
fi

echo "remove security group"
sg_name=${env}-seed-o11y-metrics-sg
security_group_id=$(aws ec2 describe-security-groups \
  --filters "Name=vpc-id,Values=$vpc_id" "Name=group-name,Values=$sg_name" \
  --query "SecurityGroups[0].GroupId" \
  --output text)
if [ "$security_group_id" != "None" ]; then
  echo "sg ${sg_name}($security_group_id) found, trying to remove"
  aws ec2 delete-security-group --group-id=$security_group_id
  while aws ec2 describe-security-groups --group-ids $security_group_id 2>/dev/null; do
    echo "waiting for security group 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 "X-Biz-Type: ${biz_type}" \
    --header "X-Org-Id: ${o11y_tenant_id}" \
    --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
