#!/bin/bash
set -exo pipefail

args=$1

k8sName=$(echo "$args" | yq ".k8s.name")
region=$(echo "$args" | yq ".region.region")
templateFile=$(echo "$args" | yq '.k8s.templatePath')
echo "k8sName=$k8sName"
echo "region=$region"
echo "templateFile=$templateFile"

exists=$(az group exists --name "$k8sName")
if [[ "$exists" != "true" ]]; then
  echo "resource group $k8sName not found"
  exit 0
fi

tenantId=$(az account show --query tenantId -o tsv)
deployClientId=$(az account show --query user.name -o tsv)
idTokenUrl="${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=${ACTIONS_ID_TOKEN_AUDIENCE}"
idToken=$(curl -H "Authorization: Bearer ${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" "${idTokenUrl}" | yq -r '.value')
az login --federated-token $idToken --service-principal -u $deployClientId -t $tenantId

aksClientId=$(az aks show \
    --name $k8sName \
    --resource-group $k8sName  \
    --query "identityProfile.kubeletidentity.clientId" \
    --output tsv)
imageRegistry=$(echo "$args" | yq '.region.imageRegistry')
acrName="${imageRegistry%%.*}"
acrId=$(az acr show --name ${acrName} --query "id" --output tsv)
az role assignment delete --assignee $aksClientId --role AcrPull --scope $acrId
echo "delete role assignment for acr $acrName"

az group delete --name "$k8sName" --yes
echo "resource group $k8sName deleted"
