#!/bin/bash
# Generated by: Claude AI via Cursor
set -x

# This script deletes an Azure HostedCluster and associated Azure resources.
# It reuses the same variables from the other scripts in this folder.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Load variables - check if vars.sh is available
if [[ -f "${SCRIPT_DIR}/vars.sh" ]]; then
    source "${SCRIPT_DIR}/vars.sh"
else
    echo "Error: vars.sh not found. Please ensure you're running this from the managed-azure directory."
    exit 1
fi

# Variables from vars.sh and user-vars.sh that we'll use
AZURE_CREDS="${AZURE_CREDS:-}"
HYPERSHIFT_BINARY_PATH="${HYPERSHIFT_BINARY_PATH:-}"
PREFIX="${PREFIX:-}"

# Local variables following the same pattern as create_basic_hosted_cluster.sh
MANAGED_RG_NAME="${PREFIX}-managed-rg"
CUSTOMER_VNET_RG_NAME="${PREFIX}-customer-vnet-rg"
CUSTOMER_NSG_RG_NAME="${PREFIX}-customer-nsg-rg"
CLUSTER_NAME="${PREFIX}-hc"

# Validate required variables
if [[ -z "$AZURE_CREDS" ]]; then
    echo "Error: AZURE_CREDS is not set. Please check your user-vars.sh file."
    exit 1
fi

if [[ -z "$HYPERSHIFT_BINARY_PATH" ]]; then
    echo "Error: HYPERSHIFT_BINARY_PATH is not set. Please check your user-vars.sh file."
    exit 1
fi

if [[ -z "$PREFIX" ]]; then
    echo "Error: PREFIX is not set. Please check your user-vars.sh file."
    exit 1
fi

# Delete the hosted cluster using hypershift destroy command
${HYPERSHIFT_BINARY_PATH}/hypershift destroy cluster azure \
    --name "$CLUSTER_NAME" \
    --azure-creds "$AZURE_CREDS" \
    --resource-group-name "$MANAGED_RG_NAME"

if [ $? -ne 0 ]; then
    echo "Error: Failed to destroy hosted cluster $CLUSTER_NAME"
    exit 1
fi

# Clean up the customer resource groups that were created for this cluster

# Delete customer NSG resource group
if az group show --name "$CUSTOMER_NSG_RG_NAME" >/dev/null 2>&1; then
    az group delete --name "$CUSTOMER_NSG_RG_NAME" --yes --no-wait
else
    echo "Customer NSG resource group $CUSTOMER_NSG_RG_NAME does not exist or already deleted"
fi

# Delete customer VNET resource group  
if az group show --name "$CUSTOMER_VNET_RG_NAME" >/dev/null 2>&1; then
    az group delete --name "$CUSTOMER_VNET_RG_NAME" --yes --no-wait
else
    echo "Customer VNET resource group $CUSTOMER_VNET_RG_NAME does not exist or already deleted"
fi

# Delete managed resource group (this contains the cluster resources)
if az group show --name "$MANAGED_RG_NAME" >/dev/null 2>&1; then
    az group delete --name "$MANAGED_RG_NAME" --yes --no-wait
else
    echo "Managed resource group $MANAGED_RG_NAME does not exist or already deleted"
fi

echo "Hosted cluster deletion completed. Resource group deletions are running in the background."
echo "You can check the status with: az group list --query \"[?starts_with(name, '$PREFIX')]\""

set +x