#Requires -RunAsAdministrator

<#
.SYNOPSIS
    Installs the Sami Home Network Root CA certificate to the Trusted Root Certification Authorities store.

.DESCRIPTION
    This script downloads the root CA certificate from ca.sami, verifies its fingerprint,
    and installs it to the local machine's trusted root store. This allows all *.sami domains
    to be trusted system-wide without browser warnings.

.NOTES
    Requires Administrator privileges.
    For use with DashCA - https://ca.sami
#>

$ErrorActionPreference = "Stop"

# Configuration
$CertUrl = "https://ca.sami/root.crt"
$ExpectedFingerprint = "0898A563F5A1A2585F02D7A8A25487E6BC33969F9B5DB053622 07FAF9621290E"
$TempFile = "$env:TEMP\sami-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 " DashCA Installer" -ForegroundColor $Cyan
Write-Host " Sami Home Network Root CA" -ForegroundColor $Cyan
Write-Host "========================================" -ForegroundColor $Cyan
Write-Host ""

# Step 1: Download certificate
Write-Host "[1/4] Downloading certificate from $CertUrl..." -ForegroundColor $Cyan
try {
    $ProgressPreference = 'SilentlyContinue' # Disable progress bar for faster download
    Invoke-WebRequest -Uri $CertUrl -OutFile $TempFile -UseBasicParsing -ErrorAction Stop
    Write-Host "      ✓ Certificate downloaded" -ForegroundColor $Green
} catch {
    Write-Host "      ✗ Failed to download certificate" -ForegroundColor $Red
    Write-Host "        Error: $_" -ForegroundColor $Red
    Write-Host ""
    Write-Host "Troubleshooting:" -ForegroundColor $Yellow
    Write-Host "  - Ensure you are on the Tailnet/network where ca.sami is accessible" -ForegroundColor $Yellow
    Write-Host "  - Try accessing https://ca.sami in your browser first" -ForegroundColor $Yellow
    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 "      ✗ 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
        Write-Host "This could indicate a man-in-the-middle attack or certificate renewal." -ForegroundColor $Red
        Write-Host "Please verify with your network administrator before proceeding." -ForegroundColor $Red
        exit 1
    }

    Write-Host "      ✓ Fingerprint verified: $Fingerprint" -ForegroundColor $Green
} catch {
    Write-Host "      ✗ Failed to verify fingerprint" -ForegroundColor $Red
    Write-Host "        Error: $_" -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 "      ℹ Certificate already installed" -ForegroundColor $Yellow
    Write-Host "        Subject: $($ExistingCert.Subject)" -ForegroundColor $Yellow
    Write-Host "        Not After: $($ExistingCert.NotAfter)" -ForegroundColor $Yellow
    Remove-Item $TempFile -Force
    Write-Host ""
    Write-Host "The Sami Home Network Root CA is already trusted on this system." -ForegroundColor $Green
    Write-Host "No further action needed!" -ForegroundColor $Green
    Write-Host ""
    exit 0
}
Write-Host "      ✓ Certificate not yet installed, proceeding..." -ForegroundColor $Green

# Step 4: Install certificate
Write-Host "[4/4] Installing certificate to Trusted Root store..." -ForegroundColor $Cyan
try {
    $ImportedCert = Import-Certificate -FilePath $TempFile -CertStoreLocation Cert:\LocalMachine\Root -ErrorAction Stop
    Write-Host "      ✓ Certificate installed successfully" -ForegroundColor $Green
    Write-Host "        Subject: $($ImportedCert.Subject)" -ForegroundColor $Green
    Write-Host "        Thumbprint: $($ImportedCert.Thumbprint)" -ForegroundColor $Green
} catch {
    Write-Host "      ✗ Failed to install certificate" -ForegroundColor $Red
    Write-Host "        Error: $_" -ForegroundColor $Red
    Remove-Item $TempFile -Force -ErrorAction SilentlyContinue
    Write-Host ""
    Write-Host "Installation failed. Please ensure you are running as Administrator." -ForegroundColor $Red
    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 "The Sami Home Network Root CA has been installed to your Trusted Root store." -ForegroundColor $Green
Write-Host ""
Write-Host "What's next:" -ForegroundColor $Cyan
Write-Host "  ✓ All *.sami domains will now be trusted system-wide" -ForegroundColor $Green
Write-Host "  ✓ Browsers (Edge, Chrome, Firefox) will no longer show security warnings" -ForegroundColor $Green
Write-Host "  ✓ Applications will trust HTTPS connections to your local services" -ForegroundColor $Green
Write-Host ""
Write-Host "Test it out:" -ForegroundColor $Cyan
Write-Host "  Visit https://status.sami or any other *.sami service" -ForegroundColor $Yellow
Write-Host "  The connection should show as secure with no warnings" -ForegroundColor $Yellow
Write-Host ""
