param(
    [string]$Configuration = "Release",
    [string]$Platform = "x64",
    [string]$CertificateSubject = "CN=OlivePrivate",
    [string]$CertificatePassword = "Embargo-Boned-Flight6",
    [switch]$Yes
)

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

$scriptRoot = Split-Path -Parent $PSCommandPath
$repoRoot = Split-Path -Parent $scriptRoot
$projectPath = Join-Path $repoRoot "Olive\Olive.csproj"
$manifestPath = Join-Path $repoRoot "Olive\Package.appxmanifest"
$packageRoot = Join-Path $repoRoot "dist\OlivePackage"
$privateRoot = Join-Path $repoRoot "dist\private"
$certPath = Join-Path $packageRoot "OlivePrivate.cer"
$pfxPath = Join-Path $privateRoot "OlivePrivate.pfx"

function Write-Step([string]$Message) {
    Write-Host "==> $Message" -ForegroundColor Cyan
}

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

    Write-Host "This script will:" -ForegroundColor Yellow
    Write-Host "- create or reuse a CurrentUser code-signing certificate: $CertificateSubject"
    Write-Host "- export a private PFX to: $pfxPath"
    Write-Host "- export a public CER to: $certPath"
    Write-Host "- build and sign the Olive MSIX"
    Write-Host "- prepare a shareable folder: $packageRoot"
    $answer = Read-Host "Continue? Type YES"
    if ($answer -ne "YES") {
        throw "Cancelled by user."
    }
}

Confirm-Continue

if (-not (Test-Path -LiteralPath $projectPath)) {
    throw "Project not found: $projectPath"
}

if (-not (Test-Path -LiteralPath $manifestPath)) {
    throw "Manifest not found: $manifestPath"
}

[xml]$manifest = Get-Content -LiteralPath $manifestPath
$packageVersion = $manifest.Package.Identity.Version

New-Item -ItemType Directory -Force -Path $packageRoot | Out-Null
New-Item -ItemType Directory -Force -Path $privateRoot | Out-Null

Write-Step "Creating or reusing signing certificate"
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Subject -eq $CertificateSubject } | Select-Object -First 1
if ($null -eq $cert) {
    $cert = New-SelfSignedCertificate `
        -Type Custom `
        -Subject $CertificateSubject `
        -KeyUsage DigitalSignature `
        -FriendlyName "Olive private signing" `
        -CertStoreLocation "Cert:\CurrentUser\My" `
        -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3")
}

Write-Step "Exporting certificate files"
$securePassword = ConvertTo-SecureString $CertificatePassword -AsPlainText -Force
Export-Certificate -Cert $cert -FilePath $certPath -Force | Out-Null
Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $securePassword -Force | Out-Null

Write-Step "Publishing signed MSIX"
dotnet publish $projectPath `
    -c $Configuration `
    -p:Platform=$Platform `
    -p:GenerateAppxPackageOnBuild=true `
    -p:AppxPackageSigningEnabled=true `
    -p:PackageCertificateThumbprint=$($cert.Thumbprint)

if ($LASTEXITCODE -ne 0) {
    throw "dotnet publish failed with exit code $LASTEXITCODE."
}

Write-Step "Copying MSIX to dist"
$publishOutput = Join-Path $repoRoot "Olive\bin\$Platform\$Configuration\net10.0-windows10.0.22621.0\win-$Platform"
$expectedMsix = Join-Path $publishOutput "Olive_${packageVersion}_${Platform}.msix"
$msix = if (Test-Path -LiteralPath $expectedMsix) {
    Get-Item -LiteralPath $expectedMsix
} else {
    Get-ChildItem -Path (Join-Path $repoRoot "Olive\AppPackages") -Filter "Olive_${packageVersion}_${Platform}.msix" -Recurse |
        Sort-Object LastWriteTime -Descending |
        Select-Object -First 1
}

if ($null -eq $msix) {
    throw "No MSIX package was generated for version $packageVersion and platform $Platform."
}

Get-ChildItem -Path $packageRoot -Filter "*.msix" | Remove-Item -Force
Copy-Item -LiteralPath $msix.FullName -Destination (Join-Path $packageRoot $msix.Name) -Force
Copy-Item -LiteralPath (Join-Path $scriptRoot "Install-Olive.ps1") -Destination (Join-Path $packageRoot "Install-Olive.ps1") -Force
Copy-Item -LiteralPath (Join-Path $scriptRoot "Uninstall-Olive.ps1") -Destination (Join-Path $packageRoot "Uninstall-Olive.ps1") -Force
Copy-Item -LiteralPath (Join-Path $scriptRoot "Install-Olive.cmd") -Destination (Join-Path $packageRoot "Install-Olive.cmd") -Force
Copy-Item -LiteralPath (Join-Path $scriptRoot "Uninstall-Olive.cmd") -Destination (Join-Path $packageRoot "Uninstall-Olive.cmd") -Force

Write-Host ""
Write-Host "Package ready:" -ForegroundColor Green
Write-Host $packageRoot
Write-Host ""
Write-Host "Share this folder with your friends: dist\OlivePackage" -ForegroundColor Green
Write-Host "Do not share this private signing file unless you really mean it: $pfxPath" -ForegroundColor Yellow
