# Setup SSH key for proxy tunneling only (ru.hunab.app / 149.154.64.19).
# Usage: run in PowerShell from repo root or pass path; no admin rights needed.
# The key is ONLY for SSH tunnels (-D SOCKS, -L). User ahau on server needs no extra rights.

param(
    [string]$SshDir = "$env:USERPROFILE\.ssh",
    [string]$KeyName = "id_ed25519",
    [string]$ProxyUser = "ahau",
    [string]$ProxyHost = "149.154.64.19"
)

$KeyPath = Join-Path $SshDir $KeyName
$KeyPubPath = "$KeyPath.pub"

Write-Host "=== SSH key for proxy tunnel (Cursor/Telegram) ===" -ForegroundColor Cyan
Write-Host "  Server: ${ProxyUser}@${ProxyHost} (ru.hunab.app)"
Write-Host "  Purpose: tunneling only. No shell or other rights on server."
Write-Host ""

# Ensure .ssh exists
if (-not (Test-Path $SshDir)) {
    New-Item -ItemType Directory -Path $SshDir -Force | Out-Null
    Write-Host "[OK] Created $SshDir"
} else {
    Write-Host "[OK] Directory exists: $SshDir"
}

# Check OpenSSH
try {
    $null = Get-Command ssh -ErrorAction Stop
} catch {
    Write-Host "[ERROR] OpenSSH client not found. Install: Settings -> Apps -> Optional features -> OpenSSH Client" -ForegroundColor Red
    exit 1
}

if (-not (Test-Path $KeyPath)) {
    Write-Host ""
    Write-Host "No key found at $KeyPath" -ForegroundColor Yellow
    Write-Host "  Option A: Copy id_ed25519 (and id_ed25519.pub) from your Mac to $SshDir"
    Write-Host "  Option B: Generate a new key now (only for tunneling; add .pub to server once)"
    $choice = Read-Host "Generate new key? (y/N)"
    if ($choice -match '^[yY]') {
        ssh-keygen -t ed25519 -f $KeyPath -N '""'
        if (-not (Test-Path $KeyPath)) { Write-Host "Key creation failed." -ForegroundColor Red; exit 1 }
        Write-Host "[OK] Key created: $KeyPath"
    } else {
        Write-Host "Copy id_ed25519 and id_ed25519.pub to $SshDir then run this script again."
        exit 0
    }
} else {
    Write-Host "[OK] Key exists: $KeyPath"
}

# Show public key (user must add to server if new)
if (Test-Path $KeyPubPath) {
    Write-Host ""
    Write-Host "Public key (add one line to ~/.ssh/authorized_keys of ${ProxyUser}@${ProxyHost}):" -ForegroundColor Cyan
    Write-Host (Get-Content $KeyPubPath -Raw).Trim()
    Write-Host ""
    Write-Host "On server (once): append the line above to /home/${ProxyUser}/.ssh/authorized_keys"
    Write-Host "This key is only used for tunneling; no sudo or other rights needed for ahau."
} else {
    Write-Host "[WARN] No $KeyPubPath found. Generate or copy from Mac." -ForegroundColor Yellow
}

# Test connection
Write-Host ""
Write-Host "Testing connection to ${ProxyUser}@${ProxyHost} ..."
$testResult = & ssh -i $KeyPath -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${ProxyUser}@${ProxyHost}" "echo OK" 2>&1
if ($LASTEXITCODE -eq 0 -and $testResult -eq "OK") {
    Write-Host "[OK] SSH works. You can start the tunnel (cursor-socks-tunnel.ps1 start)." -ForegroundColor Green
} else {
    Write-Host "[FAIL] SSH test failed. Ensure the public key is in authorized_keys on the server." -ForegroundColor Red
    Write-Host $testResult
    exit 1
}

# Optional: ensure config has hsites-ahau
$ConfigPath = Join-Path $SshDir "config"
$configEntry = @"
Host hsites-ahau
    HostName $ProxyHost
    User $ProxyUser
    IdentityFile ~/.ssh/$KeyName
    ServerAliveInterval 30
    ServerAliveCountMax 6
"@
if (-not (Test-Path $ConfigPath)) {
    Set-Content -Path $ConfigPath -Value $configEntry.Trim()
    Write-Host "[OK] Created $ConfigPath with Host hsites-ahau"
} elseif ((Get-Content $ConfigPath -Raw) -notmatch "hsites-ahau") {
    Add-Content -Path $ConfigPath -Value "`n$configEntry"
    Write-Host "[OK] Appended hsites-ahau to $ConfigPath"
}

Write-Host ""
Write-Host "Done. Run: .\docs\cursor\scripts\cursor-socks-tunnel.ps1 start" -ForegroundColor Green
