# DUO-RDP universal uninstall / recovery script
#
# Live uninstall on the current server:
#   1. Open PowerShell as Administrator.
#   2. Run:
#      powershell -ExecutionPolicy Bypass -File .\UnInstall.txt
#
# Offline recovery for a mounted Windows disk:
#   powershell -ExecutionPolicy Bypass -File .\UnInstall.txt -OfflineWindowsRoot F:\Windows
#
# The script removes the Credential Provider Filter first. This is intentional:
# it restores the standard Windows password provider even if later cleanup fails.

param(
  [string]$OfflineWindowsRoot = "",
  [switch]$KeepFiles,
  [switch]$KeepConfig
)

$ErrorActionPreference = "Continue"

$ProviderClsid = "{8F04B2A1-7C4C-4E47-9D26-9B8E744B2501}"
$FilterClsid = "{D6E4A825-8E89-49D8-A5B2-F30B7E681A39}"
$ServiceName = "DuoRdpAuthService"
$AppName = "DuoRdp"

function Write-Step([string]$Message) {
  Write-Host "[DUO-RDP uninstall] $Message"
}

function Assert-Admin {
  $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
  $principal = New-Object Security.Principal.WindowsPrincipal($identity)
  if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw "Run this script from an elevated PowerShell session."
  }
}

function Remove-RegTree([string]$Path) {
  if (Test-Path $Path) {
    Remove-Item -Path $Path -Recurse -Force -ErrorAction Continue
    Write-Step "Removed registry key: $Path"
  } else {
    Write-Step "Registry key is already absent: $Path"
  }
}

function Stop-ProcessByNameSafe([string]$Name) {
  Get-Process -Name $Name -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Step "Stopping process $($_.ProcessName) pid=$($_.Id)"
    Stop-Process -Id $_.Id -Force -ErrorAction Continue
  }
}

function Remove-LiveInstall {
  Assert-Admin

  $installDir = Join-Path $env:ProgramFiles $AppName
  $programDataDir = Join-Path $env:ProgramData $AppName

  Write-Step "Live uninstall on current Windows installation"
  Write-Step "Install dir: $installDir"

  Remove-RegTree "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Provider Filters\$FilterClsid"
  Remove-RegTree "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\$ProviderClsid"

  Remove-RegTree "HKLM:\SOFTWARE\Classes\CLSID\$FilterClsid"
  Remove-RegTree "HKLM:\SOFTWARE\Classes\CLSID\$ProviderClsid"

  Write-Step "Stopping service and helper processes"
  sc.exe stop $ServiceName | Out-Host
  Start-Sleep -Seconds 2
  Stop-ProcessByNameSafe "DuoRdpAdmin"
  Stop-ProcessByNameSafe "DuoRdpOtpService"
  Stop-ProcessByNameSafe "DuoRdpAuthService"

  Write-Step "Deleting service"
  sc.exe delete $ServiceName | Out-Host

  if (-not $KeepFiles) {
    if (Test-Path $installDir) {
      takeown.exe /f $installDir /r /d y | Out-Host
      icacls.exe $installDir /grant Administrators:F /t /c | Out-Host

      if ($KeepConfig) {
        Write-Step "Keeping config/log files, disabling binaries only"
        Get-ChildItem -Path $installDir -File -Include "*.dll","*.exe" -ErrorAction SilentlyContinue | ForEach-Object {
          Rename-Item -LiteralPath $_.FullName -NewName ($_.Name + ".disabled") -Force -ErrorAction Continue
        }
      } else {
        Remove-Item -LiteralPath $installDir -Recurse -Force -ErrorAction Continue
        Write-Step "Removed install dir: $installDir"
      }
    } else {
      Write-Step "Install dir is already absent"
    }

    if ((-not $KeepConfig) -and (Test-Path $programDataDir)) {
      Remove-Item -LiteralPath $programDataDir -Recurse -Force -ErrorAction Continue
      Write-Step "Removed program data dir: $programDataDir"
    }
  }

  Write-Step "Live uninstall complete. Reboot the server before testing Windows logon."
}

function Remove-OfflineInstall([string]$WindowsRoot) {
  Assert-Admin

  $windowsDir = (Resolve-Path -LiteralPath $WindowsRoot -ErrorAction Stop).Path
  $driveRoot = Split-Path -Qualifier $windowsDir
  $programFiles = Join-Path $driveRoot "Program Files"
  $programData = Join-Path $driveRoot "ProgramData"
  $installDir = Join-Path $programFiles $AppName
  $programDataDir = Join-Path $programData $AppName
  $softwareHive = Join-Path $windowsDir "System32\config\SOFTWARE"
  $systemHive = Join-Path $windowsDir "System32\config\SYSTEM"
  $softMount = "HKLM\DUORDP_OFF_SOFT"
  $sysMount = "HKLM\DUORDP_OFF_SYS"

  Write-Step "Offline recovery for Windows root: $windowsDir"
  if (!(Test-Path $softwareHive)) { throw "SOFTWARE hive not found: $softwareHive" }
  if (!(Test-Path $systemHive)) { throw "SYSTEM hive not found: $systemHive" }

  reg.exe load $softMount $softwareHive | Out-Host
  reg.exe load $sysMount $systemHive | Out-Host

  try {
    reg.exe delete "$softMount\Microsoft\Windows\CurrentVersion\Authentication\Credential Provider Filters\$FilterClsid" /f | Out-Host
    reg.exe delete "$softMount\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\$ProviderClsid" /f | Out-Host
    reg.exe delete "$softMount\Classes\CLSID\$FilterClsid" /f | Out-Host
    reg.exe delete "$softMount\Classes\CLSID\$ProviderClsid" /f | Out-Host

    reg.exe delete "$sysMount\ControlSet001\Services\$ServiceName" /f | Out-Host
    reg.exe delete "$sysMount\ControlSet002\Services\$ServiceName" /f | Out-Host
    reg.exe delete "$sysMount\CurrentControlSet\Services\$ServiceName" /f | Out-Host
  } finally {
    reg.exe unload $softMount | Out-Host
    reg.exe unload $sysMount | Out-Host
  }

  if (Test-Path $installDir) {
    takeown.exe /f $installDir /r /d y | Out-Host
    icacls.exe $installDir /grant Administrators:F /t /c | Out-Host

    if ($KeepFiles) {
      Write-Step "Keeping offline install files because -KeepFiles was specified"
    } elseif ($KeepConfig) {
      Write-Step "Keeping config/log files, disabling offline binaries only"
      Get-ChildItem -Path $installDir -File -Include "*.dll","*.exe" -ErrorAction SilentlyContinue | ForEach-Object {
        Rename-Item -LiteralPath $_.FullName -NewName ($_.Name + ".disabled") -Force -ErrorAction Continue
      }
    } else {
      Remove-Item -LiteralPath $installDir -Recurse -Force -ErrorAction Continue
      Write-Step "Removed offline install dir: $installDir"
    }
  }

  if ((-not $KeepFiles) -and (-not $KeepConfig) -and (Test-Path $programDataDir)) {
    Remove-Item -LiteralPath $programDataDir -Recurse -Force -ErrorAction Continue
    Write-Step "Removed offline program data dir: $programDataDir"
  }

  Write-Step "Offline recovery complete. Boot the server and test Windows logon."
}

try {
  if ([string]::IsNullOrWhiteSpace($OfflineWindowsRoot)) {
    Remove-LiveInstall
  } else {
    Remove-OfflineInstall -WindowsRoot $OfflineWindowsRoot
  }
} catch {
  Write-Error $_
  exit 1
}
