<#
.SYNOPSIS
    Test-sign the RioGamepad driver package. No admin required.

.DESCRIPTION
    Creates (once) a self-signed code-signing certificate in the current user's
    store, stages the built RioGamepad.sys + RioGamepad.inf into driver\package\,
    generates the security catalog with Inf2Cat, and signs both the .sys and the
    .cat with SHA-256. Exports the public cert (RIOJoyTest.cer) for the install
    step to trust.

    Order matters: the .sys is embed-signed BEFORE the catalog is generated, so the
    catalog hashes the signed binary; then the catalog itself is signed.

.PARAMETER Ewdk
    Drive or root where the EWDK is mounted (default: E:).
#>
param([string]$Ewdk = "E:")

$ErrorActionPreference = "Stop"
$scriptDir = $PSScriptRoot
$projectDir = Join-Path $scriptDir "RioGamepad"
$buildOut = Join-Path $projectDir "x64\Release"
$pkg = Join-Path $scriptDir "package"

$kitsBin = Join-Path $Ewdk "Program Files\Windows Kits\10\bin\10.0.28000.0"
$signtool = Join-Path $kitsBin "x64\signtool.exe"
$inf2cat = Join-Path $kitsBin "x86\Inf2Cat.exe"
$certName = "RIOJoy Test Cert"
$cerPath = Join-Path $scriptDir "RIOJoyTest.cer"

foreach ($tool in @($signtool, $inf2cat)) {
    if (-not (Test-Path $tool)) { throw "Tool not found: $tool (is the EWDK mounted at $Ewdk?)" }
}
if (-not (Test-Path (Join-Path $buildOut "RioGamepad.sys"))) {
    throw "RioGamepad.sys not found. Build first: driver\RioGamepad\build.cmd $Ewdk"
}

# 1. Self-signed code-signing certificate (idempotent).
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Subject -eq "CN=$certName" } | Select-Object -First 1
if (-not $cert) {
    Write-Host "Creating self-signed code-signing certificate '$certName'..."
    $cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=$certName" `
        -CertStoreLocation Cert:\CurrentUser\My -KeyExportPolicy Exportable `
        -NotAfter (Get-Date).AddYears(5)
}
Export-Certificate -Cert $cert -FilePath $cerPath -Force | Out-Null
Write-Host "Certificate thumbprint: $($cert.Thumbprint)"
Write-Host "Public cert exported to: $cerPath"

# 2. Stage the package.
if (Test-Path $pkg) { Remove-Item $pkg -Recurse -Force }
New-Item -ItemType Directory -Path $pkg | Out-Null
Copy-Item (Join-Path $buildOut "RioGamepad.sys") $pkg
Copy-Item (Join-Path $buildOut "RioGamepad.inf") $pkg

# 3. Embed-sign the .sys.
& $signtool sign /fd SHA256 /s My /n $certName (Join-Path $pkg "RioGamepad.sys")
if ($LASTEXITCODE -ne 0) { throw "signtool failed on RioGamepad.sys ($LASTEXITCODE)" }

# 4. Generate the catalog (Win10 x64).
& $inf2cat /driver:$pkg /os:10_X64 /verbose
if ($LASTEXITCODE -ne 0) { throw "inf2cat failed ($LASTEXITCODE)" }

# 5. Sign the catalog.
& $signtool sign /fd SHA256 /s My /n $certName (Join-Path $pkg "RioGamepad.cat")
if ($LASTEXITCODE -ne 0) { throw "signtool failed on RioGamepad.cat ($LASTEXITCODE)" }

Write-Host ""
Write-Host "Signed package ready in: $pkg" -ForegroundColor Green
Write-Host "Next: run driver\install.ps1 from an elevated shell to trust the cert," -ForegroundColor Yellow
Write-Host "enable test signing, and install the device." -ForegroundColor Yellow
Write-Host ""
Write-Host "(Note: 'signtool verify /pa' will fail until the cert is trusted by install.ps1 -" -ForegroundColor DarkGray
Write-Host " that is expected for a self-signed test driver.)" -ForegroundColor DarkGray
