# Ensure the script runs as Administrator
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs -WindowStyle Hidden
    exit
}

# Find all running D2R processes
$D2R_Processes = Get-Process | Where-Object { $_.ProcessName -eq "D2R" }

if ($D2R_Processes.Count -eq 0) {
    Write-Host "No running instances of Diablo II: Resurrected found."
    exit
}

foreach ($process in $D2R_Processes) {
    $d2rProcessId = $process.Id  # Using a different variable name to avoid conflicts
    Write-Host "Scanning process ID: $d2rProcessId"

    # Run handle64.exe and capture output directly (No need for a file)
    $handle_output = & "$PSScriptRoot\handle64.exe" -accepteula -a -p $d2rProcessId

    $handle_id = ""

    # Loop through each line in the handle output and look for "Check For Other Instances"
    foreach ($line in $handle_output) {
        if ($line -match "Check For Other Instances") {
            # Extract the handle ID from the output
            $fields = $line -split "\s+"
            $handle_id = $fields[1]
            Write-Host "Found handle: $line"
            break
        }
    }

    if ($handle_id -ne "") {
        Write-Host "Closing handle $handle_id for D2R instance (PID: $d2rProcessId)"
        # Close the handle silently
        & "$PSScriptRoot\handle64.exe" -p $d2rProcessId -c $handle_id -y
    } else {
        Write-Host "No 'Check For Other Instances' handle found for PID: $d2rProcessId"
    }
}

Write-Host "Done processing current D2R instances."
