# Install the K-os code signing certificate.
#
# Run as Administrator (recommended):
#   powershell -ExecutionPolicy Bypass -File scripts\install_cert.ps1
#
# Installs into TWO stores:
#   - Root            : marks the self-signed cert as a trusted root CA.
#                       Clears the signtool "chain terminated in a root which is
#                       not trusted" warning during `build.bat sign` and lets
#                       Windows fully validate the signature.
#   - TrustedPublisher: lets executables signed with this cert run without
#                       SmartScreen / "unknown publisher" prompts.
#
# Admin: installs to LocalMachine (all users on this PC).
# Non-admin: installs to CurrentUser only.

param(
    [string]$CerFile = "chaos_app.cer"
)

# If the file isn't in the current dir, also try the project root (the
# parent of the scripts/ folder — the usual cwd when running build.bat).
if (-not (Test-Path $CerFile)) {
    $alt = Join-Path (Split-Path -Parent $PSScriptRoot) $CerFile
    if (Test-Path $alt) {
        $CerFile = $alt
    }
}

if (-not (Test-Path $CerFile)) {
    Write-Host "Certificate file not found: $CerFile" -ForegroundColor Red
    Write-Host "Run scripts\create_cert.ps1 first, or pass -CerFile <path>."
    exit 1
}

$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
    [Security.Principal.WindowsBuiltInRole]::Administrator)

$scopeRoot = if ($isAdmin) { "Cert:\LocalMachine\Root" }            else { "Cert:\CurrentUser\Root" }
$scopePub  = if ($isAdmin) { "Cert:\LocalMachine\TrustedPublisher" } else { "Cert:\CurrentUser\TrustedPublisher" }
$scopeLabel = if ($isAdmin) { "machine-wide (all users)" }          else { "current user only" }

Import-Certificate -FilePath $CerFile -CertStoreLocation $scopeRoot | Out-Null
Write-Host "Installed to Trusted Root CAs [$scopeLabel]" -ForegroundColor Green

Import-Certificate -FilePath $CerFile -CertStoreLocation $scopePub  | Out-Null
Write-Host "Installed to Trusted Publishers [$scopeLabel]" -ForegroundColor Green

if (-not $isAdmin) {
    Write-Host ""
    Write-Host "Tip: run this as Administrator to install for all users on this PC." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "Done. `build.bat sign` should no longer warn about the chain." -ForegroundColor Cyan
