<#
.SYNOPSIS
    RIOJoy cockpit post-install. Installs the signed ViGEmBus virtual-controller
    driver (if absent). Must run elevated (postinstall.bat elevates for you).
    Idempotent — safe to re-run. RIOJoy is NOT registered to auto-start: the
    TeslaConsole launcher owns the app's start/stop lifecycle.

.DESCRIPTION
    Run from inside the deployed package directory (e.g. C:\games\RIOJOY). Paths
    are resolved relative to this script, so the layout is:

        <root>\app\RioJoy.Tray.exe          the published tray app (net48)
        <root>\vendor\ViGEmBus_*.exe         the signed ViGEmBus installer
        <root>\install-rio.ps1               (this file)

    ViGEmBus is WHQL/attestation-signed: it installs with NO test signing, NO
    Secure Boot change, and NO reboot. The RIO appears to games as a standard
    Xbox 360 controller.

#>

$ErrorActionPreference = 'Stop'

$root      = $PSScriptRoot
$appExe    = Join-Path $root 'app\RioJoy.Tray.exe'
$vendorDir = Join-Path $root 'vendor'

# --- guards ---------------------------------------------------------------
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw 'install-rio.ps1 must run elevated. Run postinstall.bat (it elevates).'
}
if (-not (Test-Path $appExe)) { throw "App not found: $appExe (is the package complete?)." }

Write-Host '== RIOJoy post-install ==' -ForegroundColor Cyan

# 1. Install ViGEmBus if its driver service is not already present.
$svc = Get-Service -Name ViGEmBus -ErrorAction SilentlyContinue
if ($svc) {
    Write-Host "ViGEmBus already installed (service is $($svc.Status))."
} else {
    $installer = Get-ChildItem -Path $vendorDir -Filter 'ViGEmBus*.exe' -ErrorAction SilentlyContinue |
                 Select-Object -First 1
    if ($installer) {
        Write-Host "Installing ViGEmBus ($($installer.Name))..."
        $p = Start-Process -FilePath $installer.FullName `
                           -ArgumentList '/install', '/quiet', '/norestart' -Wait -PassThru
        if ($p.ExitCode -notin 0, 3010) {
            throw "ViGEmBus install failed (exit code $($p.ExitCode))."
        }
        Write-Host 'ViGEmBus installed.'
    } else {
        Write-Warning "ViGEmBus installer not found in $vendorDir — joystick output will be"
        Write-Warning "unavailable until ViGEmBus is installed (keyboard/mouse still work)."
    }
}

# RIOJoy itself is deliberately NOT registered to auto-start and NOT launched
# here: the TeslaConsole launcher starts and stops the app.

# --- summary --------------------------------------------------------------
Write-Host ''
Write-Host "RIOJoy installed to $root" -ForegroundColor Green
Write-Host 'RIOJoy is not auto-started; the TeslaConsole launcher starts and stops it.'
exit 0
