$ErrorActionPreference = "Stop"

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

try {
    $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
    $certPath = Join-Path $scriptDir "certificate.cer"
    $msixPath = Join-Path $scriptDir "latest.msix"

    Write-Host "============================================"
    Write-Host " Virtual Manager - Bootstrap Installer"
    Write-Host "============================================"
    Write-Host ""
    Write-Host "Script folder: $scriptDir"
    Write-Host "Certificate:   $certPath"
    Write-Host "MSIX package:  $msixPath"
    Write-Host ""

    if (-not (Test-IsAdministrator)) {
        throw "This installer must be run as administrator. Right-click Install Virtual Manager.bat and choose Run as administrator."
    }

    if (-not (Test-Path -LiteralPath $certPath)) {
        throw "certificate.cer was not found in the VirtualManagerFiles folder."
    }

    if (-not (Test-Path -LiteralPath $msixPath)) {
        throw "latest.msix was not found in the VirtualManagerFiles folder."
    }

    Write-Host "Installing trusted certificate..."
    Import-Certificate -FilePath $certPath -CertStoreLocation "Cert:\LocalMachine\Root" | Out-Null
    Import-Certificate -FilePath $certPath -CertStoreLocation "Cert:\LocalMachine\TrustedPeople" | Out-Null
    Write-Host "Certificate installed successfully."

    Write-Host ""
    Write-Host "Verifying package signature..."
    $expectedCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certPath)
    $signature = Get-AuthenticodeSignature -LiteralPath $msixPath

    if (-not $signature.SignerCertificate) {
        throw "MSIX package is not signed."
    }

    if ($signature.SignerCertificate.Thumbprint -ne $expectedCert.Thumbprint) {
        throw "MSIX signer does not match certificate.cer. Signer thumbprint: $($signature.SignerCertificate.Thumbprint); certificate thumbprint: $($expectedCert.Thumbprint)"
    }

    Write-Host "Package signature verified."

    Write-Host ""
    Write-Host "Installing Virtual Manager..."
    Add-AppxPackage -Path $msixPath -ForceApplicationShutdown -ErrorAction Stop
    Write-Host "Application installed successfully."

    Write-Host ""
    Write-Host "============================================"
    Write-Host " Installation complete!"
    Write-Host " You can now launch Virtual Manager."
    Write-Host "============================================"
    exit 0
} catch {
    Write-Host ""
    Write-Host "ERROR: $($_.Exception.Message)"
    if ($_.InvocationInfo.PositionMessage) {
        Write-Host ""
        Write-Host $_.InvocationInfo.PositionMessage
    }
    exit 1
}
