#!/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
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}")

# 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=crossplane-azure-providerconfig
# the syncPolicy.automated.prune flag is false, ArgoCD will not delete the resource
# we also can't delete the resource, it may created by ArgoCD before delete the app
# kubectl delete providerconfig.azure.upbound.io provider-azure

gh workflow run destroy-region-application.yaml ${common_params} -f application=crossplane-azure-provider
# the syncPolicy.automated.prune flag is false, ArgoCD will not delete the resource
# we also can't delete the resource, it may created by ArgoCD before delete the app
# kubectl delete provider.pkg.crossplane.io provider-aws-iam
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-authorization
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-compute
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-containerservice
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-managedidentity
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-network
# kubectl delete provider.pkg.crossplane.io upbound-provider-azure-storage
# kubectl delete provider.pkg.crossplane.io upbound-provider-family-aws
# kubectl delete provider.pkg.crossplane.io upbound-provider-family-azure

gh workflow run destroy-region-application.yaml ${common_params} -f application=upbound-crossplane
# the syncPolicy.automated.prune flag is false, ArgoCD will not delete the resource
# we also can't delete the resource, it may created by ArgoCD before delete the app
# kubectl delete deploy crossplane -n crossplane-system
# kubectl delete deploy crossplane-rbac-manager -n crossplane-system


