<#
.SYNOPSIS
    Remove the RioGamepad device and driver. REQUIRES AN ELEVATED shell.

.DESCRIPTION
    Removes the device node, deletes the driver package from the store, and
    (optionally) turns test signing back off and removes the trusted test cert.

.PARAMETER DisableTestSigning
    Also run 'bcdedit /set testsigning off' (needs a reboot to take effect).
.PARAMETER RemoveCert
    Also remove the RIOJoy test certificate from the machine trust stores.
#>
param(
    [switch]$DisableTestSigning,
    [switch]$RemoveCert
)

$ErrorActionPreference = "Continue"

if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw "This script must be run from an elevated (Administrator) shell."
}

# 1. Remove the device instance(s) matching our hardware id.
Write-Host "Removing RioGamepad device node(s)..."
$instances = (pnputil /enum-devices /connected /class System) 2>$null
& pnputil /remove-device /deviceid "root\RioGamepad" 2>$null

# 2. Delete the driver package(s) from the store (oem*.inf published from RioGamepad.inf).
Write-Host "Locating staged driver package..."
$drivers = pnputil /enum-drivers
$published = $null
for ($i = 0; $i -lt $drivers.Count; $i++) {
    if ($drivers[$i] -match 'Original Name:\s*RioGamepad\.inf') {
        for ($j = $i; $j -ge 0; $j--) {
            if ($drivers[$j] -match 'Published Name:\s*(oem\d+\.inf)') { $published = $Matches[1]; break }
        }
    }
}
if ($published) {
    Write-Host "Deleting $published ..."
    pnputil /delete-driver $published /uninstall /force
} else {
    Write-Host "No staged RioGamepad driver package found."
}

# 3. Remove the DirectInput / joy.cpl friendly-name registration.
$joyOemRel = "SYSTEM\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM\VID_1209&PID_5249"
foreach ($hive in @("HKLM:", "HKCU:")) {
    $key = "$hive\$joyOemRel"
    if (Test-Path $key) {
        Write-Host "Removing joy.cpl friendly-name key: $key"
        Remove-Item -Path $key -Recurse -Force -ErrorAction SilentlyContinue
    }
}

if ($RemoveCert) {
    Write-Host "Removing test certificate from trust stores..."
    Get-ChildItem Cert:\LocalMachine\Root, Cert:\LocalMachine\TrustedPublisher |
        Where-Object { $_.Subject -eq "CN=RIOJoy Test Cert" } |
        ForEach-Object { Remove-Item $_.PSPath -Force }
}

if ($DisableTestSigning) {
    Write-Host "Disabling test signing (reboot required)..."
    bcdedit /set testsigning off | Out-Null
}

Write-Host "Done."
