# Sign Executable Script for rmtPocketWatcher
# Signs the standalone executable with the self-signed certificate

param(
    [string]$ExePath = "build\windows\standalone\rmtpocketwatcher.exe",
    [string]$CertPath = "certificates\rmtPocketWatcher.pfx",
    [string]$CertPassword = $(if ($env:CERT_PASSWORD) { $env:CERT_PASSWORD } else { "rmtPocketWatcher2024!" }),
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

Write-Host "Signing rmtPocketWatcher Executable" -ForegroundColor Green
Write-Host "===================================" -ForegroundColor Green

# Check if executable exists
if (-not (Test-Path $ExePath)) {
    Write-Error "Executable not found at: $ExePath"
    Write-Host "Build the application first using .\build_windows.ps1" -ForegroundColor Yellow
    exit 1
}

# Check if certificate exists
if (-not (Test-Path $CertPath)) {
    Write-Error "Certificate not found at: $CertPath"
    Write-Host "Create a certificate first using .\create_certificate.ps1" -ForegroundColor Yellow
    exit 1
}

# Check if already signed (unless forcing)
if (-not $Force) {
    try {
        $signature = Get-AuthenticodeSignature -FilePath $ExePath
        if ($signature.Status -eq "Valid") {
            Write-Host "Executable is already signed and valid" -ForegroundColor Green
            Write-Host "Certificate: $($signature.SignerCertificate.Subject)" -ForegroundColor Cyan
            Write-Host "Use -Force to re-sign" -ForegroundColor Yellow
            return
        }
    } catch {
        # File not signed or error checking, continue with signing
    }
}

# Find SignTool
Write-Host "Looking for SignTool..." -ForegroundColor Yellow
$signtool = $null

# Common SignTool locations
$signToolPaths = @(
    "${env:ProgramFiles(x86)}\Windows Kits\10\bin\10.0.22621.0\x64\signtool.exe",
    "${env:ProgramFiles(x86)}\Windows Kits\10\bin\10.0.19041.0\x64\signtool.exe",
    "${env:ProgramFiles(x86)}\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe"
)

foreach ($path in $signToolPaths) {
    if (Test-Path $path) {
        $signtool = $path
        break
    }
}

# If not found in common locations, search for it
if (-not $signtool) {
    Write-Host "Searching for SignTool in Windows Kits..." -ForegroundColor Yellow
    $foundSignTools = Get-ChildItem -Path "${env:ProgramFiles(x86)}\Windows Kits" -Recurse -Name "signtool.exe" -ErrorAction SilentlyContinue
    if ($foundSignTools) {
        $signtool = Join-Path "${env:ProgramFiles(x86)}\Windows Kits" $foundSignTools[0]
    }
}

if (-not $signtool -or -not (Test-Path $signtool)) {
    Write-Error "SignTool not found. Please install Windows SDK."
    Write-Host "Download from: https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/" -ForegroundColor Yellow
    exit 1
}

Write-Host "Found SignTool: $signtool" -ForegroundColor Cyan

# Sign the executable
Write-Host "Signing executable: $ExePath" -ForegroundColor Yellow
try {
    & $signtool sign `
        /f $CertPath `
        /p $CertPassword `
        /fd SHA256 `
        /tr http://timestamp.digicert.com `
        /td SHA256 `
        /d "rmtPocketWatcher" `
        /du "https://git.hudsonriggs.systems/LambdaBankingConglomerate/rmtPocketWatcher" `
        $ExePath

    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ Executable signed successfully!" -ForegroundColor Green
        
        # Verify the signature
        $signature = Get-AuthenticodeSignature -FilePath $ExePath
        Write-Host "Signature Status: $($signature.Status)" -ForegroundColor Cyan
        Write-Host "Signer Certificate: $($signature.SignerCertificate.Subject)" -ForegroundColor Cyan
        Write-Host "Timestamp: $($signature.TimeStamperCertificate.NotBefore)" -ForegroundColor Cyan
        
    } else {
        Write-Error "Failed to sign executable (Exit code: $LASTEXITCODE)"
    }
} catch {
    Write-Error "Error signing executable: $($_.Exception.Message)"
}

Write-Host "`n🎉 Code signing completed!" -ForegroundColor Green
Write-Host "The executable should now be trusted by Windows" -ForegroundColor Green