core/Resources/Scripts/remove_resource_group.ps1

Param(
    [Parameter(Mandatory)]
    $EnvironmentName,
    [string]$ScriptsFolderPath = ".\Resources\Scripts"
)
. "$ScriptsFolderPath\common.ps1"

if ([string]::IsNullOrEmpty($EnvironmentName)) {
    throw "Environment Name required"
}

$resourceGroup = $null

function GetUploadedVms {
    param(
        [string]$ResourceGroup
    )
    $vms = @(Get-AzVM -ErrorAction Stop -ResourceGroupName $ResourceGroup | Where-Object { $_.Tags.ContainsKey("InstallMode") -and $_.Tags["InstallMode"] -eq "server" } | ForEach-Object {
            $nicId = $_.NetworkProfile.NetworkInterfaces[0].Id
            $nicName = ($nicId -split "/")[-1]
            $nic = Get-AzNetworkInterface -ResourceGroupName $resourceGroupName -Name $nicName -ErrorAction Stop 
            $privateIp = $nic.IpConfigurations[0].PrivateIpAddress
            [PSCustomObject]@{
                Name               = $_.Name
                Location           = $_.Location
                VmSize             = $_.HardwareProfile.VmSize
                OsType             = $_.StorageProfile.OsDisk.OsType
                Zone               = ($_.Zones[0])
                Publisher          = $_.StorageProfile.ImageReference.Publisher
                Offer              = $_.StorageProfile.ImageReference.Offer
                Sku                = $_.StorageProfile.ImageReference.Sku
                Version            = $_.StorageProfile.ImageReference.Version
                NIC                = $_.NetworkProfile.NetworkInterfaces.id
                StorageAccountType = $_.StorageProfile.OsDisk.ManagedDisk.StorageAccountType
                Disk               = $_.StorageProfile.OsDisk.Name
                Tags               = $_.Tags
                PrivateIp          = $privateIp
            }
        }  )

    return , $vms
}
 

function Get-LinuxNCacheInstallDir {
    param(
        [Parameter(Mandatory = $true)]
        [string]$VMName,

        [Parameter(Mandatory = $true)]
        [string]$ResourceGroupName
    )

    $Path = $null

    try {
        # 1. Fetch VM and check its tags
        $vm = Get-AzVM -Name $VMName -ResourceGroupName $ResourceGroupName -ErrorAction Stop
        if ($vm.Tags.ContainsKey("InstallNCacheDir") -and $vm.Tags["InstallNCacheDir"]) {
            $Path = $vm.Tags["InstallNCacheDir"]
        }
        else {
            Write-Host "No 'InstallNCacheDir' tag found on VM '$VMName'. Using default '/opt/ncache'." -ForegroundColor Yellow
            $Path = "/opt/ncache"
        }
    }
    catch {
        Write-Warning "Failed to fetch VM info for '$VMName'. Using default '/opt/ncache'. $_"
        $Path = "/opt/ncache"
    }

    # 2. Normalize slashes (Linux default)
    $Path = $Path -replace '\\', '/'

    # 3. Ensure path ends with 'ncache'
    if ($Path -notmatch "(?i)ncache$") {
        $Path = (Join-Path $Path "ncache")
    }

    return $Path
}
function DeactivateNCacheFromAllVms {
    param(
        [string]$ResourceGroupName,
        [string]$Key
    )
    $vms = GetUploadedVms -ResourceGroup $ResourceGroupName
    
    $funcDef = ${function:Get-LinuxNCacheInstallDir}.ToString()

    $jobs = foreach ($vm in $vms) {
        Start-Job -ScriptBlock {
            param($VmName, $OsType, $key, $resourceGroupName)
            $vm = Get-AzVM -Name $VMName -ResourceGroupName $ResourceGroupName -ErrorAction Stop
            if ($vm.Tags.ContainsKey("NCacheActivated") -and [System.Convert]::ToBoolean($vm.Tags["NCacheActivated"])) {
                if ($OsType -eq "Windows") {
                    $windowsScript = "Unregister-ncache -Key $key"
                    $result = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $VmName -CommandId "RunPowerShellScript" -ScriptString $windowsScript
                    foreach ($val in $result.Value) {
                        Write-Host $val.Message
                    }
                }
                else {
                    $Path = $null

                    try {
                        if ($vm.Tags.ContainsKey("InstallNCacheDir") -and $vm.Tags["InstallNCacheDir"]) {
                            $Path = $vm.Tags["InstallNCacheDir"]
                        }
                        else {
                            Write-Host "No 'InstallNCacheDir' tag found on VM '$VMName'. Using default '/opt/ncache'." -ForegroundColor Yellow
                            $Path = "/opt/ncache"
                        }
                    }
                    catch {
                        Write-Warning "Failed to fetch VM info for '$VMName'. Using default '/opt/ncache'. $_"
                        $Path = "/opt/ncache"
                    }

                    $Path = $Path -replace '\\', '/'
                    if ($Path -notmatch "(?i)ncache$") {
                        $Path = (Join-Path $Path "ncache")
                    }
                    $linuxScript = "$Path/bin/tools/unregister-ncache -key $key"
                    $result = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $VmName -CommandId "RunShellScript" -ScriptString $linuxScript
                    foreach ($val in $result.Value) {
                        Write-Host $val.Message
                    }
                }
            }
        } -ArgumentList $vm.Name, $resourceGroup.Tags["OsType"], $Key, $ResourceGroupName
    }
    $jobs | Wait-Job
    $jobs | Receive-Job
}

function UninstallNCache {
    $vms = GetUploadedVms -ResourceGroup $($resourceGroup.ResourceGroupName)

    $VmNames = @()

    foreach ($vm in $vms) {   
        $VmNames += $vm.Name
    }

    if ($resourceGroup.Tags["OsType"] -eq "Windows") {
        Uninstall-NCacheFromVMWindows -ResourceGroupName $($resourceGroup.ResourceGroupName) -VMName $VmNames

    }
    else {
        Uninstall-NCacheFromVMLinux -ResourceGroupName $($resourceGroup.ResourceGroupName) -VMName $VmNames
    }
}

function CheckIfVmsRunning {
    $running = CheckIfAllVmsAreRunning -ResourceGroup $($resourceGroup.ResourceGroupName)
    if(!$running){
        throw "This action requires all VMs to be running. Please start the stopped VMs and try again."
    }
}

function RemoveresourceGroup {
    $resourceGroup = CheckIfEnvironmentExits -Environment $EnvironmentName
    $resourceGroupName = $resourceGroup.ResourceGroupName
    CheckIfVmsRunning
    if ($resourceGroup.Tags.ContainsKey("LicenseKey")) {
        $key = $resourceGroup.Tags["LicenseKey"]
        DeactivateNCacheFromAllVms -ResourceGroupName $resourceGroupName -Key $key
    }
    Write-Host "Removing Resources"
    Remove-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue 
}
ShowExecutingCommand
if (-not (Get-AzContext)) {
    NoContext
    Connect-AzAccount
    if (Get-AzContext) {
        RemoveresourceGroup
    }
}
else {
    RemoveresourceGroup
}