core/Resources/Scripts/remove_client_node.ps1


Param(
    [string]$CacheName,
    [Parameter(Mandatory = $true)]
    [string]$ClientNode,

    [Parameter(Mandatory = $true)]
    [string]$EnvironmentName,

    [bool]$AcquireServerMapping = $false,
    [bool]$NoLogo = $false,
    [bool]$UpdateServerConfig = $false,
    [int]$Port = 8250,
    [pscredential]$Credentials,
    [string]$ScriptsFolderPath = ".\Resources\Scripts"
)

. "$ScriptsFolderPath\dashboard_common.ps1"
. "$ScriptsFolderPath\Resources_Scripts\virtual_machine.ps1"
. "$ScriptsFolderPath\common.ps1"

$resourceGroupName = $null
$resourceGroup = $null
$script:vmName = $null
$script:tagsResult = $rg.Tags
$script:allVms = $null
$script:privateIpsList = $null
$script:vmToExecuteCommandOn = $null

function GetAzureVms {
    $script:allVms = Get-AzVM -ResourceGroupName $script:resourceGroupName -ErrorAction Stop
}


function GetPrivateIps {
    $result = @()
    foreach ($vm in $script:allVms) {
        $vmName = $vm.Name
        $net = $vm.NetworkProfile
        $nicId = $net.NetworkInterfaces[0].Id
        $nicName = ($nicId -split "/")[-1]

        $nic = Get-AzNetworkInterface -ResourceGroupName $script:resourceGroupName -Name $nicName -ErrorAction Stop
        $privateIp = $nic.IpConfigurations[0].PrivateIpAddress

        $result += [pscustomobject]@{
            VMName    = $vmName
            PrivateIp = $privateIp
        }
    }

    $script:privateIpsList = $result
    $script:vmToExecuteCommandOn = $script:privateIpsList[0]
}

function GetVmPrivateIp {
    param(
        $TheVm
    )
    $net = $TheVm.NetworkProfile
    $nicId = $net.NetworkInterfaces[0].Id
    $nicName = ($nicId -split "/")[-1]
    $nic = Get-AzNetworkInterface -ResourceGroupName $script:resourceGroupName -Name $nicName
    $privateIp = $nic.IpConfigurations[0].PrivateIpAddress
    return $privateIp
}


function InvokeCommandOnLinuxServer {
    $linuxScript = AddClientNodeOnAllCachesLinux
    Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $($script:vmToExecuteCommandOn.VMName) -CommandId "RunShellScript" -ScriptString $linuxScript
}

function InvokeCommandOnWindowsServer {
    $windowsScript = AddClientNodeOnAllCachesWindows
    Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $($script:vmToExecuteCommandOn.VMName) -CommandId "RunPowerShellScript" -ScriptString $windowsScript
}

function AddClientNodeOnAllCachesWindows {
    param(
        $TheVm,
        [string]$privateIp
    )
    $cmd = ""

    if (-not $CacheName) {
        $cachesList = $TheVm.Tags["Caches"].Split(",")
        foreach ($cache in $cachesList) {
            $cmd += "Remove-ClientNode -CacheName $cache -ClientNode $ClientNode -Port $Port -Server $privateIp"
            if ($AcquireServerMapping) { $cmd += " -AcquireServerMapping" }
            if ($NoLogo) { $cmd += " -NoLogo" }
            if ($UpdateServerConfig) { $cmd += " -UpdateServerConfig" }
            if ($Credentials) { $cmd += " -Credentials $Credentials" }
            $cmd += "`n"
        }
    }
    else {
        $cmd = "Remove-ClientNode -CacheName $CacheName -ClientNode $ClientNode -Port $Port -Server $privateIp"
    }
    Invoke-AzVMRunCommand -ResourceGroupName $script:resourceGroupName -VMName $($TheVm.Name) -CommandId "RunPowerShellScript" -ScriptString $cmd
    return $cmd;
}

function AddClientNodeOnAllCachesLinux {
    param(
        $TheVm,
        [string]$privateIp
    )
    $NCacheDir = "/opt/ncache"
    if ($TheVm.Tags.ContainsKey("InstallNCacheDir") -and $TheVm.Tags["InstallNCacheDir"]) {
        $NCacheDir = $TheVm.Tags["InstallNCacheDir"]
    }
    $cmd = ""
    if (-not $CacheName) {
        $cachesList = $TheVm.Tags["Caches"].Split(",")
        if ($cachesList.count -gt 0) {
            foreach ($cache in $cachesList) {
                $cmd += "$NCacheDir/bin/tools/remove-clientnode -cacheName $cache -clientNode $ClientNode -port $Port -Server $privateIp"
                if ($AcquireServerMapping) { $cmd += " -acquireServerMapping" }
                if ($NoLogo) { $cmd += " -noLogo" }
                if ($UpdateServerConfig) { $cmd += " -updateServerConfig" }
                if ($Credentials) { $cmd += " -credentials `"$($Credentials.GetNetworkCredential().UserName):$($Credentials.GetNetworkCredential().Password)`"" }
                if ($cmd) { $cmd += "; " }  
            }
        }
    }
    else {
        $cmd += "$NCacheDir/bin/tools/remove-clientnode -cacheName $CacheName -clientNode $ClientNode -port $Port -Server $privateIp"
    }
    Invoke-AzVMRunCommand -ResourceGroupName $script:resourceGroupName -VMName $($TheVm.Name) -CommandId "RunShellScript" -ScriptString $cmd
    return $cmd
}

function InvokeCommandOnServer {

}

function GetAllCachesOnWindows {
    foreach ($vm in $script:allVms) {
        if ($vm.Tags.ContainsKey("Caches")) {
            $privateIp = GetVmPrivateIp -TheVm $vm
            AddClientNodeOnAllCachesWindows -TheVm $vm -privateIp $privateIp
            break
        }
    }
}

function GetAllCachesOnLinux {
    foreach ($vm in $script:allVms) {
        if ($vm.Tags.ContainsKey("Caches")) {
            $privateIp = GetVmPrivateIp -TheVm $vm
            AddClientNodeOnAllCachesLinux -TheVm $vm -privateIp $privateIp
            break
        }
    }
}

function Remove-NodeCacheTag {
    foreach ($vm in $script:allVms) {
        $privateIp = GetVmPrivateIp -TheVm $vm
        if ($privateIp -eq $ClientNode) {
            try {
                # Convert tags dictionary to hashtable
                $tags = @{}
                if ($vm.Tags) {
                    foreach ($k in $vm.Tags.Keys) {
                        $tags[$k] = $vm.Tags[$k]
                    }
                }

                if ($tags.ContainsKey("NodeCaches")) {
                    # Split the NodeCaches by comma, trim spaces
                    $cacheList = $tags["NodeCaches"] -split "," | ForEach-Object { $_.Trim() }

                    # Remove the target cache
                    $updatedList = $cacheList | Where-Object { $_ -ne $CacheName }

                    if ($updatedList.Count -gt 0) {
                        $tags["NodeCaches"] = $updatedList -join ","
                    }
                    else {
                        # If no NodeCaches left, drop the key
                        $tags.Remove("NodeCaches")
                    }

                    # Apply updated tags
                    Set-AzResource -ResourceId $vm.Id -Tag $tags -Force -ErrorAction Stop | Out-Null
                    
                    Update-NCAzDashboards -ScriptsFolderPath $ScriptsFolderPath -ResourceGroupName $script:resourceGroupName -CacheName $CacheName -SkipServer
                }
            }
            catch {
                Write-Output "Failed to update tags on $($vm.Name): $_"
            }


            # no need to continue loop if node is found
            break;
        }
    }    
}

function ExecuteCommands {
    $resourceGroup = CheckIfEnvironmentExits -Environment $EnvironmentName
    $script:tagsResult = $resourceGroup.Tags
    $script:resourceGroupName = $resourceGroup | Select-Object -ExpandProperty resourceGroupName
    GetAzureVms
    GetPrivateIps
    if ($resourceGroup.Tags["OsType"] -eq "Windows") {
        GetAllCachesOnWindows
    }
    else {
        GetAllCachesOnLinux
    }

    Remove-NodeCacheTag
}

    
try {
    ShowExecutingCommand
    if (-not (Get-AzContext)) {
        NoContext
        Connect-AzAccount
        if (Get-AzContext) {
            ExecuteCommands
        }
    }
    else {
        ExecuteCommands
    }
}
catch {
    Write-Error $($_.Exception.Message)
    Write-Error "Coudn't remove client node'"
}