[CmdletBinding()]
param(
    [string]$InstallDir = (Join-Path $env:ProgramFiles 'KIM Quest Remote')
)

$ErrorActionPreference = 'Stop'
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
    [Security.Principal.WindowsBuiltInRole]::Administrator
)
if (-not $IsAdmin) {
    throw 'Run rollback from a PowerShell window opened with Run as administrator.'
}

$InstallDir = [System.IO.Path]::GetFullPath($InstallDir)
$TargetExe = Join-Path $InstallDir 'KIMQuestRemoteHost.exe'
$PreviousExe = Join-Path $InstallDir 'KIMQuestRemoteHost.previous.exe'
$PatchTaskName = 'KIM Remote Auto Patcher'
Disable-ScheduledTask -TaskName $PatchTaskName -ErrorAction SilentlyContinue | Out-Null
$Running = @(
    Get-CimInstance Win32_Process -Filter "Name='KIMQuestRemoteHost.exe'" -ErrorAction SilentlyContinue
)
foreach ($Process in $Running) {
    Stop-Process -Id $Process.ProcessId -Force -ErrorAction Stop
}

if (Test-Path -LiteralPath $PreviousExe) {
    $Stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
    if (Test-Path -LiteralPath $TargetExe) {
        Copy-Item `
            -LiteralPath $TargetExe `
            -Destination (Join-Path $InstallDir "KIMQuestRemoteHost.rolled-back-$Stamp.exe") `
            -Force
    }
    Copy-Item -LiteralPath $PreviousExe -Destination $TargetExe -Force
    Start-Process -FilePath $TargetExe -WorkingDirectory $InstallDir
    Write-Host 'ROLLBACK_PREVIOUS_VERSION_PASS'
} else {
    Unregister-ScheduledTask -TaskName $PatchTaskName -Confirm:$false -ErrorAction SilentlyContinue
    Get-NetFirewallRule -DisplayName 'KIM Quest Remote Host' -ErrorAction SilentlyContinue |
        Disable-NetFirewallRule
    Write-Host 'ROLLBACK_FIRST_INSTALL_DISABLED'
}

Write-Host 'Local identity, certificates, pairing key, logs, and installed files were preserved.'
