<#
.SYNOPSIS
    RIOJoy cockpit pre-uninstall cleanup. Reverses install-rio.ps1: stops the
    running tray app, removes the logon entry, optionally uninstalls ViGEmBus,
    and clears per-user config. Must run elevated (pre-uninstall.bat elevates
    for you). Idempotent — safe to re-run, and safe to run when RIOJoy was never
    fully installed.

.DESCRIPTION
    Run from inside the deployed package directory (e.g. C:\games\RIOJoy) BEFORE
    the console deletes the folder. Stopping the tray app releases the file locks
    on app\RioJoy.Tray.exe so the folder can then be removed cleanly. This script
    does NOT delete its own folder — the console does that after this returns.

.PARAMETER KeepDriver
    Leave ViGEmBus installed (default is to uninstall it, since the RIOJoy package
    installed it). Use this if other software on the machine relies on ViGEmBus.

.PARAMETER KeepConfig
    Leave per-user config (%APPDATA%\RIOJoy) in place. Default removes it for every
    user profile on the machine.
#>
param(
    [switch]$KeepDriver,
    [switch]$KeepConfig
)

$ErrorActionPreference = 'Stop'

$root         = $PSScriptRoot
$vendorDir    = Join-Path $root 'vendor'
$runValueName = 'RIOJoy'

# --- guard ----------------------------------------------------------------
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw 'uninstall-rio.ps1 must run elevated. Run pre-uninstall.bat (it elevates).'
}

Write-Host '== RIOJoy pre-uninstall cleanup ==' -ForegroundColor Cyan

# 1. Stop the running tray app (releases locks on app\RioJoy.Tray.exe).
$procs = Get-Process -Name 'RioJoy.Tray' -ErrorAction SilentlyContinue
if ($procs) {
    Write-Host "Stopping RIOJoy ($($procs.Count) process(es))..."
    $procs | Stop-Process -Force -ErrorAction SilentlyContinue
    Start-Sleep -Milliseconds 500
} else {
    Write-Host 'RIOJoy is not running.'
}

# 2. Remove the logon entry (machine-wide Run key).
$runKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
if (Get-ItemProperty -Path $runKey -Name $runValueName -ErrorAction SilentlyContinue) {
    Write-Host 'Removing logon entry...'
    Remove-ItemProperty -Path $runKey -Name $runValueName -Force -ErrorAction SilentlyContinue
} else {
    Write-Host 'No logon entry present.'
}

# 3. Uninstall ViGEmBus (best-effort; non-fatal) unless told to keep it.
if ($KeepDriver) {
    Write-Host 'Leaving ViGEmBus installed (-KeepDriver).'
} else {
    $svc = Get-Service -Name ViGEmBus -ErrorAction SilentlyContinue
    if ($svc) {
        $installer = Get-ChildItem -Path $vendorDir -Filter 'ViGEmBus*.exe' -ErrorAction SilentlyContinue |
                     Select-Object -First 1
        if ($installer) {
            Write-Host "Uninstalling ViGEmBus ($($installer.Name))..."
            try {
                $p = Start-Process -FilePath $installer.FullName `
                                   -ArgumentList '/uninstall', '/quiet', '/norestart' -Wait -PassThru
                if ($p.ExitCode -notin 0, 3010) {
                    Write-Warning "ViGEmBus uninstall returned exit code $($p.ExitCode) (continuing)."
                } else {
                    Write-Host 'ViGEmBus uninstalled.'
                }
            } catch {
                Write-Warning "ViGEmBus uninstall failed (continuing): $($_.Exception.Message)"
            }
        } else {
            Write-Warning "ViGEmBus is installed but its installer is not in $vendorDir — skipping driver removal."
        }
    } else {
        Write-Host 'ViGEmBus is not installed.'
    }
}

# 4. Remove per-user config for every profile (best-effort) unless told to keep it.
if ($KeepConfig) {
    Write-Host 'Leaving per-user config (-KeepConfig).'
} else {
    $usersRoot = Join-Path $env:SystemDrive 'Users'
    $removed = 0
    if (Test-Path $usersRoot) {
        foreach ($profile in Get-ChildItem -Path $usersRoot -Directory -ErrorAction SilentlyContinue) {
            $cfg = Join-Path $profile.FullName 'AppData\Roaming\RIOJoy'
            if (Test-Path $cfg) {
                try {
                    Remove-Item -Path $cfg -Recurse -Force -ErrorAction Stop
                    $removed++
                } catch {
                    Write-Warning "Could not remove $cfg (continuing): $($_.Exception.Message)"
                }
            }
        }
    }
    Write-Host "Removed per-user config from $removed profile(s)."
}

# --- summary --------------------------------------------------------------
Write-Host ''
Write-Host 'RIOJoy cleanup complete. The console may now delete the RIOJoy folder.' -ForegroundColor Green
exit 0
