#Requires -RunAsAdministrator

<#
.SYNOPSIS
    Installs the DashCaddy Root CA certificate to the Trusted Root Certification Authorities store.

.DESCRIPTION
    This script downloads the root CA certificate from your DashCaddy instance, verifies its fingerprint,
    and installs it to the local machine's trusted root store.
#>

$ErrorActionPreference = "Stop"

# ==========================================
# CONFIGURATION (Injected by DashCaddy API)
# ==========================================
$CertUrl = "{{CERT_URL}}"
$ExpectedFingerprint = "{{CERT_FINGERPRINT}}"
# ==========================================

$TempFile = "$env:TEMP\dashcaddy-root-ca.crt"

# Colors
$Red = [System.ConsoleColor]::Red
$Green = [System.ConsoleColor]::Green
$Cyan = [System.ConsoleColor]::Cyan
$Yellow = [System.ConsoleColor]::Yellow

Write-Host ""
Write-Host "========================================" -ForegroundColor $Cyan
Write-Host " DashCaddy Certificate Installer" -ForegroundColor $Cyan
Write-Host "========================================" -ForegroundColor $Cyan
Write-Host ""

# Step 1: Download certificate
Write-Host "[1/4] Downloading certificate..." -ForegroundColor $Cyan
try {
    $ProgressPreference = 'SilentlyContinue'

    # Bypass SSL validation — the user doesn't trust the CA yet, that's the whole point
    if (-not ([System.Management.Automation.PSTypeName]'TrustAllCertsPolicy').Type) {
        Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem) { return true; }
}
"@
    }
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

    Invoke-WebRequest -Uri $CertUrl -OutFile $TempFile -UseBasicParsing -ErrorAction Stop
    Write-Host "      OK  Certificate downloaded" -ForegroundColor $Green
} catch {
    Write-Host "      FAIL  Failed to download certificate from $CertUrl" -ForegroundColor $Red
    Write-Host "        Error: $_" -ForegroundColor $Red
    exit 1
}

# Step 2: Verify fingerprint
Write-Host "[2/4] Verifying certificate fingerprint..." -ForegroundColor $Cyan
try {
    $Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($TempFile)
    $Fingerprint = $Cert.Thumbprint

    $NormalizedExpected = $ExpectedFingerprint -replace '[:\s]', ''
    $NormalizedActual = $Fingerprint -replace '[:\s]', ''

    if ($NormalizedActual -ne $NormalizedExpected) {
        Write-Host "      FAIL  Fingerprint mismatch!" -ForegroundColor $Red
        Write-Host "        Expected: $ExpectedFingerprint" -ForegroundColor $Yellow
        Write-Host "        Got:      $Fingerprint" -ForegroundColor $Red
        Remove-Item $TempFile -Force
        Write-Host ""
        Write-Host "SECURITY WARNING: The downloaded certificate does not match the expected fingerprint." -ForegroundColor $Red
        exit 1
    }
    Write-Host "      OK  Fingerprint verified" -ForegroundColor $Green
} catch {
    Write-Host "      FAIL  Failed to verify fingerprint: $_" -ForegroundColor $Red
    Remove-Item $TempFile -Force -ErrorAction SilentlyContinue
    exit 1
}

# Step 3: Check if already installed
Write-Host "[3/4] Checking for existing certificate..." -ForegroundColor $Cyan
$ExistingCert = Get-ChildItem -Path Cert:\LocalMachine\Root | Where-Object { $_.Thumbprint -eq $Fingerprint }
if ($ExistingCert) {
    Write-Host "      INFO  Certificate already installed" -ForegroundColor $Yellow
    Remove-Item $TempFile -Force
    Write-Host ""
    Write-Host "The DashCaddy Root CA is already trusted on this system." -ForegroundColor $Green
    Start-Sleep -Seconds 3
    exit 0
}
Write-Host "      OK  Not yet installed, proceeding..." -ForegroundColor $Green

# Step 4: Install certificate
Write-Host "[4/4] Installing to Trusted Root store..." -ForegroundColor $Cyan
try {
    $ImportedCert = Import-Certificate -FilePath $TempFile -CertStoreLocation Cert:\LocalMachine\Root -ErrorAction Stop
    Write-Host "      OK  Certificate installed successfully" -ForegroundColor $Green
} catch {
    Write-Host "      FAIL  Failed to install certificate. Ensure you are running as Administrator." -ForegroundColor $Red
    Remove-Item $TempFile -Force -ErrorAction SilentlyContinue
    exit 1
}

# Cleanup
Remove-Item $TempFile -Force -ErrorAction SilentlyContinue

Write-Host ""
Write-Host "========================================" -ForegroundColor $Green
Write-Host " SUCCESS!" -ForegroundColor $Green
Write-Host "========================================" -ForegroundColor $Green
Write-Host ""
Write-Host "Your browser will now trust DashCaddy apps." -ForegroundColor $Green
Write-Host "You may need to restart your browser for changes to take effect." -ForegroundColor $Yellow
Write-Host ""
Start-Sleep -Seconds 3
