# Self-Signed Certificate Creation Script for rmtPocketWatcher
# Creates a code signing certificate for Windows applications

param(
    [string]$CertName = "Lambda Banking Conglomerate",
    [string]$AppName = "rmtPocketWatcher",
    [int]$ValidYears = 3,
    [switch]$Force = $false
)

$ErrorActionPreference = "Stop"

Write-Host "Creating Self-Signed Certificate for $AppName" -ForegroundColor Green
Write-Host "================================================" -ForegroundColor Green

# Certificate paths
$CertDir = "certificates"
$CertPath = "$CertDir\$AppName.pfx"
$CerPath = "$CertDir\$AppName.cer"
$Password = "rmtPocketWatcher2024!"

# Create certificates directory
if (-not (Test-Path $CertDir)) {
    New-Item -ItemType Directory -Path $CertDir -Force | Out-Null
    Write-Host "Created certificates directory: $CertDir" -ForegroundColor Yellow
}

# Check if certificate already exists
if ((Test-Path $CertPath) -and -not $Force) {
    Write-Host "Certificate already exists at: $CertPath" -ForegroundColor Yellow
    Write-Host "Use -Force to recreate the certificate" -ForegroundColor Yellow
    
    # Check if certificate is still valid
    try {
        $cert = Get-PfxCertificate -FilePath $CertPath
        $daysUntilExpiry = ($cert.NotAfter - (Get-Date)).Days
        
        if ($daysUntilExpiry -gt 30) {
            Write-Host "Current certificate is valid for $daysUntilExpiry more days" -ForegroundColor Green
            Write-Host "Certificate Subject: $($cert.Subject)" -ForegroundColor Cyan
            Write-Host "Certificate Thumbprint: $($cert.Thumbprint)" -ForegroundColor Cyan
            return
        } else {
            Write-Host "Certificate expires in $daysUntilExpiry days, recreating..." -ForegroundColor Yellow
            $Force = $true
        }
    } catch {
        Write-Host "Existing certificate is invalid, recreating..." -ForegroundColor Yellow
        $Force = $true
    }
}

# Remove existing certificate if forcing recreation
if ($Force -and (Test-Path $CertPath)) {
    Remove-Item $CertPath -Force
    Write-Host "Removed existing certificate" -ForegroundColor Yellow
}

Write-Host "Creating new self-signed certificate..." -ForegroundColor Yellow

# Create the certificate
$notAfter = (Get-Date).AddYears($ValidYears)
$cert = New-SelfSignedCertificate `
    -Type CodeSigningCert `
    -Subject "CN=$CertName, O=$CertName, C=US" `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
    -KeyExportPolicy Exportable `
    -KeyUsage DigitalSignature `
    -NotAfter $notAfter `
    -CertStoreLocation "Cert:\CurrentUser\My"

Write-Host "✅ Certificate created successfully" -ForegroundColor Green
Write-Host "Certificate Thumbprint: $($cert.Thumbprint)" -ForegroundColor Cyan
Write-Host "Valid Until: $($cert.NotAfter)" -ForegroundColor Cyan

# Export certificate to PFX (with private key)
$securePassword = ConvertTo-SecureString -String $Password -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath $CertPath -Password $securePassword | Out-Null
Write-Host "✅ Exported PFX certificate to: $CertPath" -ForegroundColor Green

# Export certificate to CER (public key only, for distribution)
Export-Certificate -Cert $cert -FilePath $CerPath | Out-Null
Write-Host "✅ Exported CER certificate to: $CerPath" -ForegroundColor Green

# Install certificate to Trusted Root (requires admin)
Write-Host "Installing certificate to Trusted Root Certification Authorities..." -ForegroundColor Yellow
try {
    # Check if running as administrator
    $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
    
    if ($isAdmin) {
        Import-Certificate -FilePath $CerPath -CertStoreLocation "Cert:\LocalMachine\Root" | Out-Null
        Write-Host "✅ Certificate installed to Trusted Root (system-wide)" -ForegroundColor Green
    } else {
        Import-Certificate -FilePath $CerPath -CertStoreLocation "Cert:\CurrentUser\Root" | Out-Null
        Write-Host "✅ Certificate installed to Trusted Root (current user)" -ForegroundColor Green
        Write-Host "⚠️  Run as Administrator to install system-wide" -ForegroundColor Yellow
    }
} catch {
    Write-Host "❌ Failed to install certificate to Trusted Root: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "You may need to install it manually" -ForegroundColor Yellow
}

# Create certificate info file
$certInfo = @"
rmtPocketWatcher Code Signing Certificate
========================================

Certificate Details:
- Subject: $($cert.Subject)
- Thumbprint: $($cert.Thumbprint)
- Valid From: $($cert.NotBefore)
- Valid Until: $($cert.NotAfter)
- Algorithm: $($cert.SignatureAlgorithm.FriendlyName)

Files Created:
- $CertPath (PFX with private key - keep secure!)
- $CerPath (Public certificate for distribution)

Password: $Password

Usage:
- Use the PFX file for signing applications
- Distribute the CER file to users who need to trust your apps
- Keep the PFX file secure and never share it publicly

Installation Instructions for Users:
1. Double-click $CerPath
2. Click "Install Certificate"
3. Choose "Local Machine" (requires admin) or "Current User"
4. Select "Place all certificates in the following store"
5. Browse and select "Trusted Root Certification Authorities"
6. Click "Next" and "Finish"

Note: This is a self-signed certificate. For production use,
consider purchasing a certificate from a trusted CA.
"@

$certInfo | Out-File -FilePath "$CertDir\CERTIFICATE_INFO.txt" -Encoding UTF8
Write-Host "✅ Certificate information saved to: $CertDir\CERTIFICATE_INFO.txt" -ForegroundColor Green

Write-Host "`n🎉 Certificate setup completed!" -ForegroundColor Green
Write-Host "================================================" -ForegroundColor Green
Write-Host "PFX Certificate: $CertPath" -ForegroundColor Cyan
Write-Host "Public Certificate: $CerPath" -ForegroundColor Cyan
Write-Host "Password: $Password" -ForegroundColor Cyan
Write-Host "`nNext steps:" -ForegroundColor Yellow
Write-Host "1. Update your build scripts to use this certificate" -ForegroundColor White
Write-Host "2. Test signing your application" -ForegroundColor White
Write-Host "3. Distribute the .cer file to users if needed" -ForegroundColor White

# Add to .gitignore if not already there
$gitignorePath = ".gitignore"
if (Test-Path $gitignorePath) {
    $gitignoreContent = Get-Content $gitignorePath -Raw
    if ($gitignoreContent -notmatch "certificates/") {
        Add-Content $gitignorePath "`n# Code signing certificates`ncertificates/*.pfx`ncertificates/*.p12"
        Write-Host "✅ Added certificate files to .gitignore" -ForegroundColor Green
    }
}