param(
    [switch]$UseAddAppxPackage,
    [switch]$Yes
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$scriptRoot = Split-Path -Parent $PSCommandPath
$msix = Get-ChildItem -Path $scriptRoot -Filter "*.msix" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$cert = Get-ChildItem -Path $scriptRoot -Filter "*.cer" | Sort-Object LastWriteTime -Descending | Select-Object -First 1

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

function Confirm-Continue {
    if ($Yes) {
        return
    }

    Write-Host "This script will install Olive for the current Windows user." -ForegroundColor Yellow
    Write-Host "It will import the public certificate into Cert:\LocalMachine\Root. Administrator rights are required."
    Write-Host "It will open the MSIX package found next to this script."
    Write-Host "It will not configure your Klipy API key. You do that later in Olive settings."
    $answer = Read-Host "Continue? Type YES"
    if ($answer -ne "YES") {
        throw "Cancelled by user."
    }
}

function Wait-ForCertificate {
    param(
        [string]$Thumbprint,
        [int]$TimeoutSeconds = 10
    )

    $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
    do {
        $root = Get-ChildItem Cert:\LocalMachine\Root | Where-Object { $_.Thumbprint -eq $Thumbprint } | Select-Object -First 1
        if ($null -ne $root) {
            return
        }

        Start-Sleep -Milliseconds 300
    } while ((Get-Date) -lt $deadline)

    throw "Certificate was imported, but Windows did not report it in Cert:\LocalMachine\Root before timeout."
}

if ($null -eq $msix) {
    throw "No .msix file found next to this script."
}

if ($null -eq $cert) {
    throw "No .cer certificate found next to this script."
}

if (-not (Test-IsAdministrator)) {
    throw "Administrator rights are required to import the Olive signing certificate into Cert:\LocalMachine\Root. Run Install-Olive.cmd, or start PowerShell as administrator."
}

Confirm-Continue

Write-Host "==> Importing certificate into LocalMachine Root" -ForegroundColor Cyan
Import-Certificate -FilePath $cert.FullName -CertStoreLocation Cert:\LocalMachine\Root | Out-Null

$trustedCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($cert.FullName)
Wait-ForCertificate -Thumbprint $trustedCert.Thumbprint

if ($UseAddAppxPackage) {
    Write-Host "==> Installing MSIX with Add-AppxPackage" -ForegroundColor Cyan
    Add-AppxPackage -Path $msix.FullName
} else {
    Write-Host "==> Opening MSIX with Windows App Installer" -ForegroundColor Cyan
    Start-Process -FilePath $msix.FullName -Wait
}

Write-Host ""
Write-Host "Olive install flow completed." -ForegroundColor Green
Write-Host "Restart PowerToys, open Command Palette, launch 'Klipy GIF Picker', then set the Klipy API key in Olive settings."
