Files
dune-dashboard/launcher.ps1
T
Reditus 4a94bf68ce fix: director ConfigMap name, CSRF, ServerSetScale replicas + error handling
- Fix ConfigMap name derivation (strip funcom-seabass- prefix from namespace)
- Fix CSRF token missing on all 6 director POST handlers (fetch -> csrfFetch)
- Add ServerSetScale replicas management to director map cards
- Merge webOverrideCfg into cfg so UI shows active runtime overrides
- Auto-refresh after Apply and reset button state on all handlers
- Surface JSON error bodies in error banner instead of silent fail
- Fix SSL SAN handling for IP vs DNS common name
- Fix Let's Encrypt certbot paths to use project-root certbot/ dir
- Fix deploys_ok to reflect actual K8s availability
- Add active server deployment matching with restart buttons
2026-05-29 11:55:57 +01:00

3120 lines
149 KiB
PowerShell

# Dune Awakening Dashboard - Unified Launcher
# This script handles both setup and starting the dashboard.
# Run this script and choose what you want to do.
$ErrorActionPreference = "Continue"
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location -LiteralPath $ProjectRoot
# ── Logging Setup ─────────────────────────────────────────────────────
$LogDir = Join-Path $ProjectRoot "logs"
$LauncherLogDir = Join-Path $LogDir "launcher"
if (-not (Test-Path $LauncherLogDir)) {
New-Item -ItemType Directory -Path $LauncherLogDir -Force | Out-Null
}
$LogDate = Get-Date -Format "yyyy-MM-dd"
$LogTime = Get-Date -Format "HH-mm-ss"
# ── Log Sanitization ──────────────────────────────────────────────────
# Redacts identifiable information before writing to log files.
# Console output remains unchanged for user visibility.
# Track sensitive values dynamically discovered during runtime
$SensitiveValues = @{
ServerIP = $null
SSHKeyPath = $null
Namespace = $null
HostID = $null
Tokens = @()
Passwords = @()
FuncomIDs = @()
JWTs = @()
}
function Register-SensitiveValue {
param(
[string]$Key,
[string]$Value
)
if ($Value -and $Value.Length -gt 3) {
$SensitiveValues[$Key] = $Value
}
}
function Sanitize-LogMessage {
param([string]$Message)
if (-not $Message) { return $Message }
$sanitized = $Message
# JWT tokens (eyJ...)
$sanitized = $sanitized -replace 'eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', '<JWT_REDACTED>'
# Base64-encoded secrets (long base64 strings ending with ==)
$sanitized = $sanitized -replace '[A-Za-z0-9+/]{30,}={0,2}', {
$match = $args[0].Value
if ($match -match '^[A-Za-z0-9+/]{20,}={0,2}$') {
return '<BASE64_REDACTED>'
}
return $match
}
# IP addresses (IPv4)
$sanitized = $sanitized -replace '\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b', '<IP_REDACTED>'
# SSH key file paths
$sanitized = $sanitized -replace '(?:[A-Z]:\\|~)[^\s]*sshKey[^\s]*', '<SSH_KEY_PATH_REDACTED>'
$sanitized = $sanitized -replace '(?:[A-Z]:\\|~)[^\s]*dune-tunnel-key[^\s]*', '<SSH_KEY_PATH_REDACTED>'
$sanitized = $sanitized -replace '(?:[A-Z]:\\|~)[^\s]*id_ed25519[^\s]*', '<SSH_KEY_PATH_REDACTED>'
$sanitized = $sanitized -replace '(?:[A-Z]:\\|~)[^\s]*id_rsa[^\s]*', '<SSH_KEY_PATH_REDACTED>'
# K8s namespace (funcom-seabass-...)
$sanitized = $sanitized -replace 'funcom-seabass-[A-Za-z0-9-]+', '<NAMESPACE_REDACTED>'
# Host IDs (B17A5F036D1F7882 format - 16 hex chars)
$sanitized = $sanitized -replace '\b[A-F0-9]{16}\b', '<HOST_ID_REDACTED>'
# Service auth tokens in env var format
$sanitized = $sanitized -replace '(?:RMQ_HTTP_TOKEN_AUTH_SECRET|ServiceAuthToken|ServiceAuthKey)=.+', '$1=<TOKEN_REDACTED>'
# Password-like patterns
$sanitized = $sanitized -replace '(?i)(?:password|passwd|pwd|secret|token)\s*[=:]\s*\S+', '$1=<REDACTED>'
# Funcom IDs (FID-xxxxx or similar patterns)
$sanitized = $sanitized -replace '\bFID-[A-Za-z0-9-]+\b', '<FUNCOM_ID_REDACTED>'
# Dynamic sensitive values registered at runtime
foreach ($key in $SensitiveValues.Keys) {
$val = $SensitiveValues[$key]
if ($val -and $val.Length -gt 4) {
$escapedVal = [regex]::Escape($val)
$sanitized = $sanitized -replace $escapedVal, "<$key`_REDACTED>"
}
}
return $sanitized
}
function Write-Log {
param(
[Parameter(Mandatory=$true)]
[string]$Message,
[ValidateSet("INFO", "WARN", "ERROR", "DEBUG")]
[string]$Level = "INFO",
[ValidateSet("general", "ssh", "k8s", "database", "dashboard", "setup", "diagnostics")]
[string]$Category = "general"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
$sanitizedEntry = Sanitize-LogMessage -Message $logEntry
$categoryDir = Join-Path $LauncherLogDir $category
if (-not (Test-Path $categoryDir)) {
New-Item -ItemType Directory -Path $categoryDir -Force | Out-Null
}
$logFile = Join-Path $categoryDir "$LogDate.log"
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
switch ($Level) {
"ERROR" { Write-Host $logEntry -ForegroundColor Red }
"WARN" { Write-Host $logEntry -ForegroundColor Yellow }
"DEBUG" { Write-Host $logEntry -ForegroundColor DarkGray }
default { Write-Host $logEntry -ForegroundColor White }
}
}
function Write-LogNoConsole {
param(
[Parameter(Mandatory=$true)]
[string]$Message,
[ValidateSet("INFO", "WARN", "ERROR", "DEBUG")]
[string]$Level = "INFO",
[ValidateSet("general", "ssh", "k8s", "database", "dashboard", "setup", "diagnostics")]
[string]$Category = "general"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
$sanitizedEntry = Sanitize-LogMessage -Message $logEntry
$categoryDir = Join-Path $LauncherLogDir $category
if (-not (Test-Path $categoryDir)) {
New-Item -ItemType Directory -Path $categoryDir -Force | Out-Null
}
$logFile = Join-Path $categoryDir "$LogDate.log"
Add-Content -Path $logFile -Value $sanitizedEntry -Encoding UTF8
}
function Start-LogSession {
param([string]$SessionName = "Launcher Session")
$sessionFile = Join-Path $LauncherLogDir "$LogDate-$LogTime-session.log"
$header = "=" * 60
$sanitizedName = Sanitize-LogMessage -Message $SessionName
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
Add-Content -Path $sessionFile -Value "$sanitizedName - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -Encoding UTF8
Add-Content -Path $sessionFile -Value (Sanitize-LogMessage -Message $header) -Encoding UTF8
return $sessionFile
}
function Write-Step {
param([string]$Name, [string]$Category = "general")
if (-not $global:StepCounter) { $global:StepCounter = @{} }
if (-not $global:StepCounter[$Category]) { $global:StepCounter[$Category] = 0 }
$global:StepCounter[$Category]++
$num = $global:StepCounter[$Category]
Write-Log -Message "[$num] $Name" -Level "INFO" -Category $Category
}
function Write-Success {
param([string]$Message, [string]$Category = "general")
Write-Log -Message $Message -Level "INFO" -Category $Category
}
function Write-DebugLog {
param([string]$Message, [string]$Category = "general")
Write-Log -Message $Message -Level "DEBUG" -Category $Category
}
function Write-Sep {
param([string]$Title, [string]$Category = "general")
$sep = "-" * 55
$msg = if ($Title) { "$Title $sep" } else { $sep }
$logFile = Join-Path $LauncherLogDir "$Category\$LogDate.log"
if (-not (Test-Path (Split-Path $logFile))) {
New-Item -ItemType Directory -Path (Split-Path $logFile) -Force | Out-Null
}
Add-Content -Path $logFile -Value $msg -Encoding UTF8
Write-Host $msg -ForegroundColor DarkGray
}
$Script:LogIndent = 0
function Push-Indent {
$Script:LogIndent++
}
function Pop-Indent {
$Script:LogIndent = [Math]::Max(0, $Script:LogIndent - 1)
}
function Write-LogStyled {
param(
[string]$Message,
[string]$Level = "INFO",
[string]$Category = "general"
)
$prefix = if ($Script:LogIndent -gt 0) { " " * $Script:LogIndent } else { "" }
Write-Log -Message "$prefix$Message" -Level $Level -Category $Category
}
# ── Log Rotation & Cleanup ────────────────────────────────────────────
# Prevents logs from growing unbounded.
# - Deletes log files older than $LogRetentionDays
# - Truncates current logs exceeding $LogMaxSizeMB
$LogRetentionDays = 30
$LogMaxSizeMB = 10
function Invoke-LogCleanup {
$cutoffDate = (Get-Date).AddDays(-$LogRetentionDays)
$maxBytes = $LogMaxSizeMB * 1MB
$deletedCount = 0
$truncatedCount = 0
if (-not (Test-Path $LauncherLogDir)) { return }
# Delete old log files by creation date
Get-ChildItem -Path $LauncherLogDir -Recurse -File -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.CreationTime -lt $cutoffDate) {
Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
$deletedCount++
}
}
# Truncate oversized current logs (keep last 5000 lines)
Get-ChildItem -Path $LauncherLogDir -Recurse -File -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.Length -gt $maxBytes) {
try {
$lines = Get-Content -LiteralPath $_.FullName -Tail 5000
$header = "[LOG ROTATED] Previous entries truncated due to size limit ($LogMaxSizeMB MB)`n"
$header + ($lines -join "`n") | Set-Content -LiteralPath $_.FullName -Encoding UTF8 -Force
$truncatedCount++
} catch {}
}
}
# Remove empty category directories
Get-ChildItem -Path $LauncherLogDir -Directory -Recurse -ErrorAction SilentlyContinue | ForEach-Object {
$items = Get-ChildItem -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
if ($items.Count -eq 0) {
Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
}
}
if ($deletedCount -gt 0 -or $truncatedCount -gt 0) {
Write-LogNoConsole -Message "Log cleanup: deleted $deletedCount old files, truncated $truncatedCount oversized files" -Category "general"
}
}
# Run cleanup at launcher startup
Invoke-LogCleanup
# ── Helper Functions ──────────────────────────────────────────────────
function Show-Banner {
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Awakening Dashboard" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
}
function Show-Menu {
Write-Host " What would you like to do?" -ForegroundColor Cyan
Write-Host ""
Write-Host " [1] Start Dashboard" -ForegroundColor White
Write-Host " Launch the dashboard web interface." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [2] Run Setup" -ForegroundColor White
Write-Host " Configure the dashboard for the first time, or reconfigure." -ForegroundColor DarkGray
Write-Host " Sets up SSH, SSL, firewall rules, and saves settings.yaml." -ForegroundColor DarkGray
Write-Host " WARNING: Re-running setup will wipe your current settings." -ForegroundColor Yellow
Write-Host ""
Write-Host " [3] Run Diagnostics" -ForegroundColor White
Write-Host " Check your system for common issues that could block the dashboard." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [4] Install CA Certificate" -ForegroundColor White
Write-Host " Install the local CA certificate into Windows Trusted Root store." -ForegroundColor DarkGray
Write-Host " Removes browser SSL warnings on this machine only." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [5] Clean & Reinstall CA Certificate" -ForegroundColor White
Write-Host " Remove all old Dune Dashboard CA certificates and install a fresh one." -ForegroundColor DarkGray
Write-Host " Use this if you have duplicate or expired CA certificates." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [6] Start Dashboard (Debug Mode)" -ForegroundColor Magenta
Write-Host " Launch dashboard with full debug logging enabled." -ForegroundColor DarkGray
Write-Host " Logs written to logs/debug.log - includes SSH, API, DB, K8s details." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
Write-Host " NOTE: Not complete. Do not report bugs. May not even work." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [8] Reset to Factory Defaults" -ForegroundColor Red
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [9] Repair Game Database" -ForegroundColor Yellow
Write-Host " Fixes dashboard schema ownership so game updates won't break." -ForegroundColor DarkGray
Write-Host " Run this if game servers fail to start after an update." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [10] Clean up Old Dashboard Schema" -ForegroundColor Red
Write-Host " Drops the old dashboard schema from the game database." -ForegroundColor DarkGray
Write-Host " Only run after confirming dashboard migrated successfully." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [Q] Quit" -ForegroundColor White
Write-Host ""
}
function Test-Python {
try {
$pythonVersion = python --version 2>&1
Write-Host " Python: $pythonVersion" -ForegroundColor Green
return $true
} catch {
Write-Host " Python: NOT FOUND" -ForegroundColor Red
Write-Host ""
Write-Host " Python 3.8+ is required but not detected on your system." -ForegroundColor Yellow
Write-Host ""
$installPython = Read-Host " Would you like to install Python automatically? (Y/n)"
if ($installPython -ne 'n' -and $installPython -ne 'N') {
Write-Host ""
Write-Host " Installing Python via winget..." -ForegroundColor Yellow
try {
winget install Python.Python.3.11 -e --accept-package-agreements --accept-source-agreements --silent 2>$null | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host " Python installed successfully." -ForegroundColor Green
Write-Host " Please restart your terminal and run the launcher again." -ForegroundColor Cyan
return $false
}
} catch {}
Write-Host " winget installation failed or unavailable." -ForegroundColor Yellow
Write-Host ""
Write-Host " Please install Python 3.8+ manually:" -ForegroundColor Cyan
Write-Host " 1. Download from https://www.python.org/downloads/" -ForegroundColor White
Write-Host " 2. During installation, check: [x] Add Python to PATH" -ForegroundColor White
Write-Host " 3. Restart your terminal and run the launcher again." -ForegroundColor White
return $false
} else {
Write-Host ""
Write-Host " Please install Python 3.8+ manually:" -ForegroundColor Cyan
Write-Host " 1. Download from https://www.python.org/downloads/" -ForegroundColor White
Write-Host " 2. During installation, check: [x] Add Python to PATH" -ForegroundColor White
Write-Host " 3. Restart your terminal and run the launcher again." -ForegroundColor White
return $false
}
}
}
function Test-Dependencies {
Write-Host " Checking Python dependencies..." -ForegroundColor Yellow
$installed = @()
$missing = @()
$required = @(
@{ Name = 'flask'; Pkg = 'Flask' },
@{ Name = 'flask_socketio'; Pkg = 'Flask-SocketIO' },
@{ Name = 'socketio'; Pkg = 'python-socketio' },
@{ Name = 'psycopg2'; Pkg = 'psycopg2-binary' },
@{ Name = 'paramiko'; Pkg = 'paramiko' },
@{ Name = 'yaml'; Pkg = 'PyYAML' },
@{ Name = 'flask_login'; Pkg = 'Flask-Login' },
@{ Name = 'flask_wtf'; Pkg = 'Flask-WTF' },
@{ Name = 'flask_limiter'; Pkg = 'Flask-Limiter' },
@{ Name = 'cryptography'; Pkg = 'cryptography' },
@{ Name = 'argon2'; Pkg = 'argon2-cffi' }
)
foreach ($mod in $required) {
$result = python -c "import $($mod.Name)" 2>$null
if ($LASTEXITCODE -eq 0) {
$installed += $mod.Pkg
} else {
$missing += $mod.Pkg
}
}
if ($installed.Count -gt 0) {
Write-Host " Already installed ($($installed.Count)):" -ForegroundColor Green
foreach ($pkg in $installed) { Write-Host " - $pkg" -ForegroundColor DarkGray }
}
if ($missing.Count -gt 0) {
Write-Host ""
Write-Host " Missing packages ($($missing.Count)):" -ForegroundColor Yellow
foreach ($pkg in $missing) { Write-Host " - $pkg" -ForegroundColor Yellow }
Write-Host ""
$installDeps = Read-Host " Install missing dependencies? (Y/n)"
if ($installDeps -eq 'n' -or $installDeps -eq 'N') {
Write-Host ""
Write-Host " Installation cancelled. Cannot continue without required packages." -ForegroundColor Red
return $false
}
Write-Host ""
Write-Host " Installing dependencies..." -ForegroundColor Yellow
pip install -r (Join-Path $ProjectRoot "requirements.txt") --quiet
if ($LASTEXITCODE -eq 0) {
Write-Host " Dependencies installed successfully." -ForegroundColor Green
return $true
} else {
Write-Host " [WARN] Some packages may have failed to install." -ForegroundColor Yellow
return $false
}
} else {
Write-Host " All dependencies are installed." -ForegroundColor Green
return $true
}
}
function Test-SshKey {
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
$sshKeySrc = $null
# Try to read SSH key from settings
if (Test-Path $settingsFile) {
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
if ($settings.server -and $settings.server.ssh_key -and $settings.server.ssh_key -ne 'null') {
$sshKeySrc = $settings.server.ssh_key
}
}
}
# Search for SSH key
$keyPaths = @(
$sshKeySrc,
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
(Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"),
"$env:TEMP\dune-tunnel-key",
"$env:USERPROFILE\.ssh\id_ed25519",
"$env:USERPROFILE\.ssh\id_rsa"
) | Where-Object { $_ -and $_ -ne 'null' }
foreach ($kp in $keyPaths) {
if (Test-Path $kp) {
Write-Host " SSH Key: Found at $kp" -ForegroundColor Green
return $kp
}
}
Write-Host " SSH Key: NOT FOUND" -ForegroundColor Red
Write-Host ""
Write-Host " No SSH key was found. The dashboard needs an SSH key to connect to your game server." -ForegroundColor Yellow
Write-Host ""
Write-Host " Where to find your SSH key:" -ForegroundColor Cyan
Write-Host " - If you used the Dune Awakening server setup, it's at:" -ForegroundColor White
Write-Host " %LOCALAPPDATA%\DuneAwakeningServer\sshKey" -ForegroundColor DarkGray
Write-Host ""
Write-Host " - If you generated your own key, it's wherever you saved it." -ForegroundColor White
Write-Host ""
Write-Host " To fix this:" -ForegroundColor Cyan
Write-Host " 1. Locate your SSH private key file" -ForegroundColor White
Write-Host " 2. Copy it to: $ProjectRoot\internal-scripts\ssh\sshKey" -ForegroundColor White
Write-Host " 3. Or run setup again and provide the path when prompted" -ForegroundColor White
Write-Host ""
return $null
}
function Test-SshConnection {
param($sshKey, $serverHost, $serverUser)
if (-not $sshKey -or -not $serverHost -or $serverHost -eq 'YOUR_SERVER_IP') {
Write-Host " SSH Connection: SKIPPED (server not configured)" -ForegroundColor Yellow
return $false
}
Write-Host " Testing SSH connection to $serverUser@$serverHost..." -ForegroundColor Yellow
$testOut = ssh -i $sshKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${serverUser}@${serverHost}" "echo ok" 2>$null
if ($testOut -eq "ok") {
Write-Host " SSH Connection: OK" -ForegroundColor Green
return $true
} else {
Write-Host " SSH Connection: FAILED" -ForegroundColor Red
Write-Host ""
Write-Host " Could not connect to the game server via SSH." -ForegroundColor Yellow
Write-Host ""
Write-Host " Common causes:" -ForegroundColor Cyan
Write-Host " 1. The game server VM is not running" -ForegroundColor White
Write-Host " Fix: Start your Hyper-V VM or ensure the remote server is online." -ForegroundColor DarkGray
Write-Host ""
Write-Host " 2. The SSH key is incorrect or doesn't match the server" -ForegroundColor White
Write-Host " Fix: Verify the key in settings.yaml matches the key authorized on the VM." -ForegroundColor DarkGray
Write-Host ""
Write-Host " 3. The server IP in settings.yaml is wrong" -ForegroundColor White
Write-Host " Fix: Edit settings.yaml and update server.host to the correct IP." -ForegroundColor DarkGray
Write-Host ""
Write-Host " 4. A firewall is blocking SSH (port 22)" -ForegroundColor White
Write-Host " Fix: Check your network/firewall settings." -ForegroundColor DarkGray
Write-Host ""
return $false
}
}
function Test-PortAvailability {
param($port, $name)
$inUse = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Listen' }
if ($inUse) {
$proc = Get-Process -Id $inUse.OwningProcess -ErrorAction SilentlyContinue
$procName = if ($proc) { $proc.ProcessName } else { "unknown" }
Write-Host " Port $port ($name): IN USE by $procName (PID: $($inUse.OwningProcess))" -ForegroundColor Red
return $false
} else {
Write-Host " Port $port ($name): Available" -ForegroundColor Green
return $true
}
}
function Test-FirewallRule {
$fwRuleName = "DuneDashboard"
try {
$fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue
if ($fwExists) {
Write-Host " Firewall Rule '$fwRuleName': EXISTS" -ForegroundColor Green
return $true
}
} catch {}
Write-Host " Firewall Rule '$fwRuleName': NOT FOUND" -ForegroundColor Yellow
return $false
}
function Show-PortForwardGuide {
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Port Forwarding & Firewall Guide" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " If you want to access the dashboard from another device on your network" -ForegroundColor White
Write-Host " or from the internet, you need to open/forward the dashboard port." -ForegroundColor White
Write-Host ""
Write-Host " -- Home Network (Router Port Forwarding) ------------------" -ForegroundColor Cyan
Write-Host ""
Write-Host " 1. Find this computer's local IP address:" -ForegroundColor White
Write-Host " Run this command: ipconfig" -ForegroundColor DarkGray
Write-Host " Look for 'IPv4 Address' under your active network adapter." -ForegroundColor DarkGray
Write-Host " It will look like: 192.168.1.XXX or 10.0.0.XXX" -ForegroundColor DarkGray
Write-Host ""
Write-Host " 2. Log into your router's admin page:" -ForegroundColor White
Write-Host " Open a browser and go to your router's IP (usually 192.168.1.1 or 192.168.0.1)" -ForegroundColor DarkGray
Write-Host " Look for 'Port Forwarding', 'Virtual Server', or 'NAT' settings." -ForegroundColor DarkGray
Write-Host ""
Write-Host " 3. Create a port forwarding rule:" -ForegroundColor White
Write-Host " - External Port: 5050 (or your dashboard port)" -ForegroundColor DarkGray
Write-Host " - Internal Port: 5050 (or your dashboard port)" -ForegroundColor DarkGray
Write-Host " - Protocol: TCP" -ForegroundColor DarkGray
Write-Host " - Internal IP: The local IP from step 1" -ForegroundColor DarkGray
Write-Host ""
Write-Host " 4. Find your public IP address:" -ForegroundColor White
Write-Host " Visit https://api.ipify.org in your browser" -ForegroundColor DarkGray
Write-Host " Your public IP is what others use to connect: https://YOUR_PUBLIC_IP:5050" -ForegroundColor DarkGray
Write-Host ""
Write-Host " -- Windows Firewall ---------------------------------------" -ForegroundColor Cyan
Write-Host ""
Write-Host " If Windows Firewall is blocking incoming connections:" -ForegroundColor White
Write-Host ""
Write-Host " Quick fix (run as Administrator):" -ForegroundColor White
Write-Host " New-NetFirewallRule -DisplayName 'DuneDashboard' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5050" -ForegroundColor DarkGray
Write-Host ""
Write-Host " Or via the GUI:" -ForegroundColor White
Write-Host " 1. Open 'Windows Defender Firewall with Advanced Security'" -ForegroundColor DarkGray
Write-Host " 2. Click 'Inbound Rules' -> 'New Rule...'" -ForegroundColor DarkGray
Write-Host " 3. Select 'Port' -> TCP -> Specific local ports: 5050" -ForegroundColor DarkGray
Write-Host " 4. Select 'Allow the connection' -> Apply to all profiles -> Name it 'DuneDashboard'" -ForegroundColor DarkGray
Write-Host ""
Write-Host " -- Cloud Server (AWS, Azure, Hetzner, etc.) -------------" -ForegroundColor Cyan
Write-Host ""
Write-Host " If your dashboard is on a cloud server, you need to open the port" -ForegroundColor White
Write-Host " in the cloud provider's firewall/security group:" -ForegroundColor White
Write-Host ""
Write-Host " - AWS: Edit the Security Group -> Add Inbound Rule -> TCP 5050" -ForegroundColor DarkGray
Write-Host " - Azure: Edit Network Security Group -> Add Inbound Rule -> TCP 5050" -ForegroundColor DarkGray
Write-Host " - Hetzner: Edit Firewall -> Add Rule -> TCP 5050" -ForegroundColor DarkGray
Write-Host " - DigitalOcean: Edit Firewall -> Add Inbound Rule -> TCP 5050" -ForegroundColor DarkGray
Write-Host ""
Write-Host " -- Common Ports Used by the Dashboard -------------------" -ForegroundColor Cyan
Write-Host ""
Write-Host " Port 5050 - Dashboard web interface (main port)" -ForegroundColor White
Write-Host " Port 80 - HTTP to HTTPS redirect (optional)" -ForegroundColor White
Write-Host " Port 443 - HTTPS (if you change the dashboard port to 443)" -ForegroundColor White
Write-Host ""
Write-Host " -- Testing Your Connection -------------------------------" -ForegroundColor Cyan
Write-Host ""
Write-Host " From another device on the same network:" -ForegroundColor White
Write-Host " Open browser -> https://THIS_COMPUTER_IP:5050" -ForegroundColor DarkGray
Write-Host ""
Write-Host " From the internet:" -ForegroundColor White
Write-Host " Open browser -> https://YOUR_PUBLIC_IP:5050" -ForegroundColor DarkGray
Write-Host ""
Write-Host " If it doesn't work:" -ForegroundColor White
Write-Host " 1. Check Windows Firewall (see above)" -ForegroundColor DarkGray
Write-Host " 2. Check router port forwarding (see above)" -ForegroundColor DarkGray
Write-Host " 3. Check cloud provider firewall (see above)" -ForegroundColor DarkGray
Write-Host " 4. Make sure the dashboard is bound to 0.0.0.0 (not 127.0.0.1)" -ForegroundColor DarkGray
Write-Host " Check settings.yaml -> dashboard.host should be 0.0.0.0 for remote access" -ForegroundColor DarkGray
Write-Host ""
}
function Run-Diagnostics {
Show-Banner
Write-Host " Running Diagnostics..." -ForegroundColor Cyan
Write-Host ""
$issues = 0
# Python
Write-Host "[1/7] Checking Python..." -ForegroundColor Yellow
if (-not (Test-Python)) { $issues++ }
Write-Host ""
# Dependencies
Write-Host "[2/7] Checking Dependencies..." -ForegroundColor Yellow
if (-not (Test-Dependencies)) { $issues++ }
Write-Host ""
# Settings
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
Write-Host "[3/7] Checking Settings..." -ForegroundColor Yellow
if (Test-Path $settingsFile) {
Write-Host " settings.yaml: FOUND" -ForegroundColor Green
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
$hasServer = $settings.server -and $settings.server.host -and $settings.server.host -ne 'YOUR_SERVER_IP'
if ($hasServer) {
Write-Host " Server Host: $($settings.server.host)" -ForegroundColor Green
} else {
Write-Host " Server Host: NOT CONFIGURED (edit settings.yaml)" -ForegroundColor Red
$issues++
}
if ($settings.dashboard) {
Write-Host " Dashboard: $($settings.dashboard.host):$($settings.dashboard.port)" -ForegroundColor Green
if ($settings.dashboard.host -eq '0.0.0.0') {
Write-Host " (Accessible from LAN and internet)" -ForegroundColor DarkGray
} else {
Write-Host " (Only accessible from this computer)" -ForegroundColor DarkGray
}
if ($settings.dashboard.ssl_cert -and $settings.dashboard.ssl_cert -ne 'null') {
Write-Host " SSL Cert: $($settings.dashboard.ssl_cert)" -ForegroundColor Green
}
if ($settings.dashboard.ssl_domain -and $settings.dashboard.ssl_domain -ne 'null') {
Write-Host " SSL Domain: $($settings.dashboard.ssl_domain)" -ForegroundColor Green
}
}
if ($settings.auth) {
if ($settings.auth.enabled -eq $true -and $settings.auth.username -and $settings.auth.password_hash -match '^\$argon2') {
Write-Host " Auth: enabled, user: $($settings.auth.username)" -ForegroundColor Green
} else {
Write-Host " Auth: INCOMPLETE (run setup to configure)" -ForegroundColor Yellow
}
}
if (-not $settings.kubernetes -or -not $settings.kubernetes.namespace) {
Write-Host " K8s Namespace: NOT CONFIGURED" -ForegroundColor Yellow
} else {
Write-Host " K8s Namespace: $($settings.kubernetes.namespace)" -ForegroundColor Green
}
} else {
Write-Host " settings.yaml: COULD NOT READ" -ForegroundColor Red
$issues++
}
} else {
Write-Host " settings.yaml: NOT FOUND - Run setup first" -ForegroundColor Red
$issues++
}
Write-Host ""
# SSH Key
Write-Host "[4/7] Checking SSH Key..." -ForegroundColor Yellow
$sshKey = Test-SshKey
if (-not $sshKey) { $issues++ }
Write-Host ""
# SSH Connection
Write-Host "[5/7] Checking SSH Connection..." -ForegroundColor Yellow
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
$serverHost = $settings.server.host
$serverUser = $settings.server.user
if (-not (Test-SshConnection -sshKey $sshKey -serverHost $serverHost -serverUser $serverUser)) { $issues++ }
} else {
Write-Host " SSH Connection: SKIPPED (settings not available)" -ForegroundColor Yellow
}
Write-Host ""
# Port Availability
Write-Host "[6/7] Checking Port Availability..." -ForegroundColor Yellow
$dashboardPort = 5050
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
if ($settings.dashboard -and $settings.dashboard.port) {
$dashboardPort = [int]$settings.dashboard.port
}
}
if (-not (Test-PortAvailability -port $dashboardPort -name "Dashboard")) { $issues++ }
Write-Host ""
# Firewall
Write-Host "[7/7] Checking Firewall..." -ForegroundColor Yellow
Test-FirewallRule | Out-Null
Write-Host ""
# Summary
Write-Host "============================================================" -ForegroundColor Cyan
if ($issues -eq 0) {
Write-Host " All local checks passed!" -ForegroundColor Green
} else {
Write-Host " Found $issues local issue(s) that may prevent the dashboard from working." -ForegroundColor Yellow
Write-Host " Review the messages above for details on how to fix each issue." -ForegroundColor Yellow
}
Write-Host ""
# SSL Certificate check
Write-Host "[CHECK] SSL Certificate..." -ForegroundColor Yellow
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
$sslCert = $null
if ($settings.dashboard -and $settings.dashboard.ssl_cert -and $settings.dashboard.ssl_cert -ne 'null') {
$sslCert = $settings.dashboard.ssl_cert
} else {
$sslCert = Join-Path $ProjectRoot "ssl\cert.pem"
}
if (Test-Path $sslCert) {
$certExpiry = (Get-PfxCertificate -FilePath $sslCert -ErrorAction SilentlyContinue).NotAfter
if ($certExpiry) {
$daysLeft = ($certExpiry - (Get-Date)).Days
if ($daysLeft -gt 30) {
Write-Host " SSL Certificate: VALID ($daysLeft days until expiry)" -ForegroundColor Green
} elseif ($daysLeft -gt 0) {
Write-Host " SSL Certificate: EXPIRING SOON ($daysLeft days left)" -ForegroundColor Yellow
} else {
Write-Host " SSL Certificate: EXPIRED" -ForegroundColor Red
$issues++
}
} else {
Write-Host " SSL Certificate file found but could not read expiry" -ForegroundColor Yellow
}
} else {
Write-Host " SSL Certificate: NOT FOUND (dashboard will run without HTTPS)" -ForegroundColor Yellow
}
} else {
Write-Host " SSL Certificate: SKIPPED (settings not available)" -ForegroundColor Yellow
}
Write-Host ""
# Database connectivity check
Write-Host "[CHECK] Database Connectivity..." -ForegroundColor Yellow
$dbPort = 15433
if ($settingsJson) {
$settings = $settingsJson | ConvertFrom-Json
if ($settings.database -and $settings.database.port) {
$dbPort = [int]$settings.database.port
}
}
$dbCheckPath = Join-Path $ProjectRoot "scripts\db_check.py"
if (Test-Path $dbCheckPath) {
$dbResult = python $dbCheckPath $dbPort 2>$null
if ($dbResult -eq "ok") {
Write-Host " Database: CONNECTED (port $dbPort)" -ForegroundColor Green
} else {
Write-Host " Database: NOT REACHABLE (port $dbPort) - $dbResult" -ForegroundColor Yellow
Write-Host " (This is normal if the SSH tunnel is not established yet)" -ForegroundColor DarkGray
}
} else {
Write-Host " Database check script not found" -ForegroundColor Yellow
}
Write-Host ""
# certbot availability
Write-Host "[CHECK] Let's Encrypt certbot..." -ForegroundColor Yellow
$certbotPath = (Get-Command "certbot" -ErrorAction SilentlyContinue).Source
if ($certbotPath) {
Write-Host " certbot: FOUND at $certbotPath" -ForegroundColor Green
} else {
$certbotAsModule = python -m certbot --version 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " certbot: FOUND (python module)" -ForegroundColor Green
} else {
Write-Host " certbot: NOT FOUND (only needed for Let's Encrypt SSL)" -ForegroundColor DarkGray
}
}
Write-Host ""
# Backend dependencies check
Write-Host "[CHECK] New Dashboard Backend Dependencies..." -ForegroundColor Yellow
$backendReqs = Join-Path $ProjectRoot "backend\requirements.txt"
if (Test-Path $backendReqs) {
python -c "import pydantic, httpx, uvicorn" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " Backend deps: INSTALLED" -ForegroundColor Green
} else {
Write-Host " Backend deps: MISSING (run: pip install -r backend\requirements.txt)" -ForegroundColor Yellow
$issues++
}
} else {
Write-Host " Backend deps: SKIPPED (no backend/requirements.txt)" -ForegroundColor DarkGray
}
Write-Host ""
# Offer port forward guide
Write-Host " Would you like to see the Port Forwarding & Firewall guide? (y/N)" -ForegroundColor Cyan
$showGuide = Read-Host " "
if ($showGuide -eq 'y' -or $showGuide -eq 'Y') {
Show-PortForwardGuide
}
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
}
function Install-CaCert {
$CaCertPath = Join-Path $ProjectRoot "ssl\ca.pem"
if (-not (Test-Path $CaCertPath)) {
Write-Host ""
Write-Host " [ERROR] CA certificate not found at ssl\ca.pem" -ForegroundColor Red
Write-Host ""
Write-Host " The CA certificate hasn't been generated yet." -ForegroundColor Yellow
Write-Host " Run Setup first to generate the local CA certificate." -ForegroundColor Yellow
return
}
Write-Host ""
Write-Host " Installing Dune Dashboard CA certificate..." -ForegroundColor Yellow
Write-Host ""
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host " [WARN] Not running as Administrator." -ForegroundColor Yellow
Write-Host " Starting a new elevated PowerShell window to install the CA cert..." -ForegroundColor Yellow
Write-Host ""
$elevatedScript = "certutil -addstore -f 'Root' '$CaCertPath'; Write-Host ''; Read-Host 'Press Enter to close'"
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $elevatedScript -Verb RunAs -Wait
Write-Host " CA certificate installation complete." -ForegroundColor Green
} else {
certutil -addstore -f "Root" $CaCertPath
if ($LASTEXITCODE -eq 0) {
Write-Host " CA certificate installed to Trusted Root Certification Authorities." -ForegroundColor Green
} else {
Write-Host " [WARN] certutil failed. Try running as Administrator." -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host " Restart your browser for the change to take effect." -ForegroundColor Cyan
Write-Host ""
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
}
function Clean-CaCerts {
$CaCertPath = Join-Path $ProjectRoot "ssl\ca.pem"
if (-not (Test-Path $CaCertPath)) {
Write-Host ""
Write-Host " [ERROR] CA certificate not found at ssl\ca.pem" -ForegroundColor Red
Write-Host ""
Write-Host " The CA certificate hasn't been generated yet." -ForegroundColor Yellow
Write-Host " Run Setup first to generate the local CA certificate." -ForegroundColor Yellow
return
}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Dashboard - CA Certificate Cleanup" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " Removing all existing Dune Dashboard CA certificates..." -ForegroundColor Yellow
Write-Host ""
try {
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', 'CurrentUser')
$store.Open('ReadWrite')
$certs = $store.Certificates | Where-Object { $_.Subject -like '*Dune Dashboard*' }
Write-Host " Found $($certs.Count) in CurrentUser store" -ForegroundColor DarkGray
foreach ($c in $certs) {
$store.Remove($c)
Write-Host " Removed: $($c.Thumbprint)" -ForegroundColor DarkGray
}
$store.Close()
} catch {
Write-Host " [WARN] Could not clean CurrentUser store: $_" -ForegroundColor Yellow
}
try {
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', 'LocalMachine')
$store.Open('ReadWrite')
$certs = $store.Certificates | Where-Object { $_.Subject -like '*Dune Dashboard*' }
Write-Host " Found $($certs.Count) in LocalMachine store" -ForegroundColor DarkGray
foreach ($c in $certs) {
$store.Remove($c)
Write-Host " Removed: $($c.Thumbprint)" -ForegroundColor DarkGray
}
$store.Close()
} catch {
Write-Host " [WARN] Could not clean LocalMachine store (may require Administrator): $_" -ForegroundColor Yellow
}
Write-Host ""
Write-Host " Installing fresh CA certificate..." -ForegroundColor Yellow
Write-Host ""
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host " [WARN] Not running as Administrator." -ForegroundColor Yellow
Write-Host " Starting a new elevated PowerShell window to install the CA cert..." -ForegroundColor Yellow
Write-Host ""
$elevatedScript = "certutil -addstore -f 'Root' '$CaCertPath'; Write-Host ''; Read-Host 'Press Enter to close'"
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $elevatedScript -Verb RunAs -Wait
} else {
certutil -addstore -f "Root" $CaCertPath
}
if ($LASTEXITCODE -eq 0) {
Write-Host " CA certificate cleaned and reinstalled successfully." -ForegroundColor Green
} else {
Write-Host " [WARN] Could not install certificate. Try running as Administrator." -ForegroundColor Yellow
}
Write-Host ""
Write-Host " Restart your browser for the change to take effect." -ForegroundColor Cyan
Write-Host ""
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
}
function Reset-ToFactoryDefaults {
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Reset to Factory Defaults" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " [WARNING] This will permanently delete the following:" -ForegroundColor Red
Write-Host " - settings.yaml (all configuration)" -ForegroundColor Yellow
Write-Host " - logs/, app/logs/, backend/logs/ (log files)" -ForegroundColor Yellow
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
Write-Host " - __pycache__/ (Python cache in app/, backend/)" -ForegroundColor Yellow
Write-Host " - frontend/node_modules/ (npm dependencies)" -ForegroundColor Yellow
Write-Host " - internal-scripts/ssh/ (copied SSH key)" -ForegroundColor Yellow
Write-Host " - Temp scripts (read_settings*, hash_pw*, ssh_*, etc.)" -ForegroundColor Yellow
Write-Host " - Test & build artifacts" -ForegroundColor Yellow
Write-Host ""
Write-Host " This cannot be undone. You will need to run Setup again." -ForegroundColor Red
Write-Host ""
$confirmation = Read-Host " Type 'yes' to confirm"
if ($confirmation -ne "yes") {
Write-Host ""
Write-Host " Reset cancelled. No changes made." -ForegroundColor Yellow
Write-Host ""
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
return
}
Write-Host ""
Write-Host " Wiping all dashboard data..." -ForegroundColor Yellow
Write-Host ""
$count = 0
# -- Core config & data --
if (Test-Path (Join-Path $ProjectRoot "settings.yaml")) { Remove-Item (Join-Path $ProjectRoot "settings.yaml") -Force; Write-Host " Deleted settings.yaml" -ForegroundColor Green; $count++ }
if (Test-Path (Join-Path $ProjectRoot "instance")) { Remove-Item (Join-Path $ProjectRoot "instance") -Recurse -Force; Write-Host " Deleted instance/" -ForegroundColor Green; $count++ }
# -- SSL certificates --
if (Test-Path (Join-Path $ProjectRoot "ssl")) { Remove-Item (Join-Path $ProjectRoot "ssl") -Recurse -Force; Write-Host " Deleted ssl/" -ForegroundColor Green; $count++ }
# -- Log directories --
$logDirs = @("logs", "app\logs", "backend\logs")
foreach ($ld in $logDirs) {
$lp = Join-Path $ProjectRoot $ld
if (Test-Path $lp) { Remove-Item $lp -Recurse -Force; Write-Host " Deleted $ld/" -ForegroundColor Green; $count++ }
}
# -- SSH key --
$sshKeyDir = Join-Path $ProjectRoot "internal-scripts\ssh"
if (Test-Path $sshKeyDir) { Remove-Item $sshKeyDir -Recurse -Force; Write-Host " Deleted internal-scripts/ssh/" -ForegroundColor Green; $count++ }
# -- Python __pycache__ directories --
$cacheSearchPaths = @("app", "backend")
$totalCacheDirs = 0
foreach ($csp in $cacheSearchPaths) {
$cspPath = Join-Path $ProjectRoot $csp
if (Test-Path $cspPath) {
$dirs = Get-ChildItem -Path $cspPath -Recurse -Directory -Filter "__pycache__" -ErrorAction SilentlyContinue
foreach ($d in $dirs) { Remove-Item $d.FullName -Recurse -Force; $totalCacheDirs++ }
}
}
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; $totalCacheDirs++ }
if ($totalCacheDirs -gt 0) { Write-Host " Deleted $totalCacheDirs __pycache__ folder(s)" -ForegroundColor Green; $count++ }
# -- frontend/node_modules --
if (Test-Path (Join-Path $ProjectRoot "frontend\node_modules")) { Remove-Item (Join-Path $ProjectRoot "frontend\node_modules") -Recurse -Force; Write-Host " Deleted frontend/node_modules/" -ForegroundColor Green; $count++ }
if (Test-Path (Join-Path $ProjectRoot "frontend\package-lock.json")) { Remove-Item (Join-Path $ProjectRoot "frontend\package-lock.json") -Force; Write-Host " Deleted frontend/package-lock.json" -ForegroundColor Green; $count++ }
# -- Temp scripts generated during setup --
$tempPatterns = @("read_settings*.py", "hash_pw*.py", "ssh_cmd.bat", "ssh_pf_*.bat", "certbot-out.txt", "temp_*.py", "temp_*.ps1", "temp_*.sh", "check_*.py", "fix_*.py", "parse_*.ps1", "find_*.py")
$tempDeleted = 0
foreach ($pat in $tempPatterns) {
$matches = Get-ChildItem -Path $ProjectRoot -Filter $pat -ErrorAction SilentlyContinue
foreach ($m in $matches) { Remove-Item $m.FullName -Force; $tempDeleted++ }
}
if ($tempDeleted -gt 0) { Write-Host " Deleted $tempDeleted temp script(s)" -ForegroundColor Green; $count++ }
# -- Test & build artifacts --
$artifactDirs = @(".pytest_cache", "htmlcov", "build", "backups", "frontend\.vite")
foreach ($ad in $artifactDirs) {
$ap = Join-Path $ProjectRoot $ad
if (Test-Path $ap) { Remove-Item $ap -Recurse -Force; Write-Host " Deleted $ad/" -ForegroundColor Green; $count++ }
}
$artifactFiles = @(".coverage", "coverage.xml")
foreach ($af in $artifactFiles) {
$afp = Join-Path $ProjectRoot $af
if (Test-Path $afp) { Remove-Item $afp -Force; Write-Host " Deleted $af" -ForegroundColor Green; $count++ }
}
Write-Host ""
if ($count -gt 0) {
Write-Host " Reset complete! Dashboard has been restored to a clean state." -ForegroundColor Green
Write-Host " Run Setup to configure the dashboard from scratch." -ForegroundColor Cyan
} else {
Write-Host " No dashboard data found. Nothing to wipe." -ForegroundColor Yellow
}
Write-Host ""
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
}
function Run-Setup {
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Awakening Dashboard - Setup" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
# Check if this is a re-run
$IsReRun = (Test-Path (Join-Path $ProjectRoot "settings.yaml")) -or (Test-Path (Join-Path $ProjectRoot "logs")) -or (Test-Path (Join-Path $ProjectRoot "instance")) -or (Test-Path (Join-Path $ProjectRoot "ssl"))
$QuickReconfig = $false
if ($IsReRun) {
Write-Host " [INFO] Existing dashboard data detected!" -ForegroundColor Yellow
Write-Host ""
Write-Host " What would you like to do?" -ForegroundColor Cyan
Write-Host " [1] Full re-setup from scratch" -ForegroundColor White
Write-Host " Wipes all settings, logs, certs, and starts fresh." -ForegroundColor DarkGray
Write-Host " [2] Quick reconfig" -ForegroundColor White
Write-Host " Keep existing files. Update settings with current values as defaults." -ForegroundColor DarkGray
Write-Host " [C] Cancel" -ForegroundColor White
Write-Host ""
$reconfigChoice = Read-Host " Choose [1/2/C]"
if ($reconfigChoice -eq 'C' -or $reconfigChoice -eq 'c') {
Write-Host ""
Write-Host " Setup cancelled. No changes made." -ForegroundColor Yellow
return
}
if ($reconfigChoice -eq '2') {
$QuickReconfig = $true
Write-Host ""
Write-Host " Reading existing settings..." -ForegroundColor Yellow
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if ($settingsJson) {
$existing = $settingsJson | ConvertFrom-Json
if ($existing.server) {
if ($existing.server.host -and $existing.server.host -ne 'YOUR_SERVER_IP') { $VmHost = $existing.server.host }
if ($existing.server.user) { $ServerUser = $existing.server.user }
if ($existing.server.local_ip -and $existing.server.local_ip -ne 'null') { $vmIp = $existing.server.local_ip }
if ($existing.server.ssh_key -and $existing.server.ssh_key -ne 'null' -and $existing.server.ssh_key -ne '') { $FoundKey = $existing.server.ssh_key }
}
if ($existing.dashboard) {
if ($existing.dashboard.port) { $DashboardPort = [string]$existing.dashboard.port }
if ($existing.dashboard.host -eq '0.0.0.0') { $EnableRemote = $true }
if ($existing.dashboard.ssl_domain -and $existing.dashboard.ssl_domain -ne 'null') { $DomainName = $existing.dashboard.ssl_domain }
if ($existing.dashboard.ssl_email -and $existing.dashboard.ssl_email -ne 'null') { $LeEmail = $existing.dashboard.ssl_email }
if ($existing.dashboard.ssl_cert -and $existing.dashboard.ssl_cert -ne 'null') { $SslCert = "'$($existing.dashboard.ssl_cert)'" }
if ($existing.dashboard.ssl_key -and $existing.dashboard.ssl_key -ne 'null') { $SslKey = "'$($existing.dashboard.ssl_key)'" }
}
if ($existing.database) { if ($existing.database.port) { $DbPort = [string]$existing.database.port } }
if ($existing.kubernetes) { if ($existing.kubernetes.namespace) { $K8sNamespace = $existing.kubernetes.namespace } }
if ($existing.director) { if ($existing.director.port) { $DirectorPort = [string]$existing.director.port } }
if ($existing.filebrowser) { if ($existing.filebrowser.port) { $FileBrowserPort = [string]$existing.filebrowser.port } }
if ($existing.auth) { if ($existing.auth.username) { $AuthUser = $existing.auth.username } }
Write-Host " Existing settings loaded. You'll be prompted to review or change each value." -ForegroundColor Green
} else {
Write-Host " [WARN] Could not read existing settings. Falling back to full setup." -ForegroundColor Yellow
$QuickReconfig = $false
}
}
if (-not $QuickReconfig) {
Write-Host " [WARNING] This will wipe existing data and start fresh!" -ForegroundColor Red
Write-Host ""
Write-Host " This will WIPE the following:" -ForegroundColor Yellow
Write-Host " - settings.yaml (configuration)" -ForegroundColor Yellow
Write-Host " - logs/ (all log files)" -ForegroundColor Yellow
Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow
Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow
Write-Host " - __pycache__/ (Python cache)" -ForegroundColor Yellow
Write-Host ""
Write-Host " Are you sure? Type 'yes' to confirm." -ForegroundColor Red
$confirmation = Read-Host " Type 'yes' to confirm"
if ($confirmation -ne "yes") {
Write-Host ""
Write-Host " Setup cancelled. No changes made." -ForegroundColor Yellow
return
}
Write-Host ""
Write-Host " Cleaning existing data..." -ForegroundColor Yellow
if (Test-Path (Join-Path $ProjectRoot "settings.yaml")) { Remove-Item (Join-Path $ProjectRoot "settings.yaml") -Force; Write-Host " Removed settings.yaml" -ForegroundColor Green }
if (Test-Path (Join-Path $ProjectRoot "logs")) { Remove-Item (Join-Path $ProjectRoot "logs") -Recurse -Force; Write-Host " Removed logs/" -ForegroundColor Green }
if (Test-Path (Join-Path $ProjectRoot "instance")) { Remove-Item (Join-Path $ProjectRoot "instance") -Recurse -Force; Write-Host " Removed instance/" -ForegroundColor Green }
if (Test-Path (Join-Path $ProjectRoot "ssl")) { Remove-Item (Join-Path $ProjectRoot "ssl") -Recurse -Force; Write-Host " Removed ssl/" -ForegroundColor Green }
if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force; Write-Host " Removed __pycache__/" -ForegroundColor Green }
$cacheDirs = Get-ChildItem -Path (Join-Path $ProjectRoot "app") -Recurse -Directory -Filter "__pycache__" -ErrorAction SilentlyContinue
foreach ($dir in $cacheDirs) { Remove-Item $dir.FullName -Recurse -Force }
if ($cacheDirs.Count -gt 0) { Write-Host " Removed $($cacheDirs.Count) Python cache folders" -ForegroundColor Green }
Write-Host " Clean complete!" -ForegroundColor Green
Write-Host ""
}
}
# Check Python
Write-Host "[1/6] Checking Python..." -ForegroundColor Yellow
try {
$pythonVersion = python --version 2>&1
Write-Host " Found: $pythonVersion" -ForegroundColor Green
} catch {
Write-Host " Python: NOT FOUND" -ForegroundColor Red
Write-Host ""
Write-Host " Python 3.8+ is required but not detected on your system." -ForegroundColor Yellow
Write-Host ""
$installPython = Read-Host " Would you like to install Python automatically? (Y/n)"
if ($installPython -ne 'n' -and $installPython -ne 'N') {
Write-Host ""
Write-Host " Installing Python via winget..." -ForegroundColor Yellow
try {
winget install Python.Python.3.11 -e --accept-package-agreements --accept-source-agreements --silent 2>$null | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host " Python installed successfully." -ForegroundColor Green
Write-Host " Please restart your terminal and run the launcher again." -ForegroundColor Cyan
return
}
} catch {}
Write-Host " winget installation failed or unavailable." -ForegroundColor Yellow
Write-Host ""
Write-Host " Please install Python 3.8+ manually:" -ForegroundColor Cyan
Write-Host " 1. Download from https://www.python.org/downloads/" -ForegroundColor White
Write-Host " 2. During installation, check: [x] Add Python to PATH" -ForegroundColor White
Write-Host " 3. Restart your terminal and run the launcher again." -ForegroundColor White
return
} else {
Write-Host ""
Write-Host " Please install Python 3.8+ manually:" -ForegroundColor Cyan
Write-Host " 1. Download from https://www.python.org/downloads/" -ForegroundColor White
Write-Host " 2. During installation, check: [x] Add Python to PATH" -ForegroundColor White
Write-Host " 3. Restart your terminal and run the launcher again." -ForegroundColor White
return
}
}
# Install dependencies
Write-Host ""
Write-Host "[2/6] Checking dependencies..." -ForegroundColor Yellow
$depInstalled = @()
$depMissing = @()
$depRequired = @(
@{ Name = 'flask'; Pkg = 'Flask' },
@{ Name = 'flask_socketio'; Pkg = 'Flask-SocketIO' },
@{ Name = 'socketio'; Pkg = 'python-socketio' },
@{ Name = 'psycopg2'; Pkg = 'psycopg2-binary' },
@{ Name = 'paramiko'; Pkg = 'paramiko' },
@{ Name = 'yaml'; Pkg = 'PyYAML' },
@{ Name = 'flask_login'; Pkg = 'Flask-Login' },
@{ Name = 'flask_wtf'; Pkg = 'Flask-WTF' },
@{ Name = 'flask_limiter'; Pkg = 'Flask-Limiter' },
@{ Name = 'cryptography'; Pkg = 'cryptography' },
@{ Name = 'argon2'; Pkg = 'argon2-cffi' }
)
foreach ($mod in $depRequired) {
$result = python -c "import $($mod.Name)" 2>$null
if ($LASTEXITCODE -eq 0) {
$depInstalled += $mod.Pkg
} else {
$depMissing += $mod.Pkg
}
}
if ($depInstalled.Count -gt 0) {
Write-Host " Already installed ($($depInstalled.Count)):" -ForegroundColor Green
foreach ($pkg in $depInstalled) { Write-Host " - $pkg" -ForegroundColor DarkGray }
}
if ($depMissing.Count -gt 0) {
Write-Host ""
Write-Host " Missing packages ($($depMissing.Count)):" -ForegroundColor Yellow
foreach ($pkg in $depMissing) { Write-Host " - $pkg" -ForegroundColor Yellow }
Write-Host ""
$installDeps = Read-Host " Install missing dependencies? (Y/n)"
if ($installDeps -eq 'n' -or $installDeps -eq 'N') {
Write-Host ""
Write-Host " Installation cancelled. Cannot continue without required packages." -ForegroundColor Red
return
}
Write-Host ""
Write-Host " Installing dependencies..." -ForegroundColor Yellow
pip install -r (Join-Path $ProjectRoot "requirements.txt") --quiet
if ($LASTEXITCODE -eq 0) {
Write-Host " Dependencies installed successfully." -ForegroundColor Green
} else {
Write-Host " [WARN] Some packages may have failed to install." -ForegroundColor Yellow
}
} else {
Write-Host " All dependencies are installed." -ForegroundColor Green
}
# Configure SSH key
Write-Host ""
Write-Host "[3/6] Configuring SSH key..." -ForegroundColor Yellow
$TargetKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
$SshKeyPaths = @(
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
"$env:TEMP\dune-tunnel-key",
"$env:TEMP\dune-awakening-server-sshKey",
$TargetKey,
(Join-Path (Split-Path $ProjectRoot) "internal-scripts\ssh\sshKey")
)
$FoundKey = $null
foreach ($path in $SshKeyPaths) {
if (Test-Path $path) {
$FoundKey = $path
break
}
}
function Fix-SshKeyPermissions($keyPath) {
if (-not (Test-Path $keyPath)) { return }
$acl = Get-Acl $keyPath
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
$acl.SetAccessRule($rule)
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators", "FullControl", "Allow")
$acl.SetAccessRule($adminRule)
Set-Acl -Path $keyPath -AclObject $acl
}
if (-not $FoundKey) {
Write-Host " [INFO] No SSH key found in standard locations." -ForegroundColor Yellow
$userKey = Read-Host " Enter path to your SSH key file (or press Enter to skip)"
if ($userKey -and (Test-Path $userKey)) {
$targetDir = Join-Path $ProjectRoot "internal-scripts\ssh"
if (-not (Test-Path $targetDir)) {
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
}
Copy-Item $userKey $TargetKey -Force
Fix-SshKeyPermissions $TargetKey
$FoundKey = $TargetKey
Write-Host " Key copied to internal-scripts\ssh\sshKey" -ForegroundColor Green
} else {
Write-Host " Skipping SSH key configuration." -ForegroundColor Yellow
$FoundKey = $null
}
} else {
if ($FoundKey -notlike "*internal-scripts*") {
$targetDir = Join-Path $ProjectRoot "internal-scripts\ssh"
if (-not (Test-Path $targetDir)) {
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
}
Copy-Item $FoundKey $TargetKey -Force
Fix-SshKeyPermissions $TargetKey
$FoundKey = $TargetKey
Write-Host " Key copied to internal-scripts\ssh\sshKey for portability" -ForegroundColor Green
} else {
Write-Host " Found: $FoundKey" -ForegroundColor Green
}
}
if (-not $QuickReconfig) {
# Auto-detect server settings
Write-Host ""
Write-Host "[4/6] Detecting server settings..." -ForegroundColor Yellow
$VmHost = "YOUR_SERVER_IP"
$HostIp = $null
$ServerUser = "dune"
$K8sNamespace = ""
$DashboardPort = "5050"
$DbPort = "15433"
$DbHost = "127.0.0.1"
$DirectorPort = "32479"
$FileBrowserPort = "18888"
$AuthUser = "admin"
$AuthPass = ""
function Test-IsLocalIP($ip) {
if ($ip -match '^192\.168\.') { return $true }
if ($ip -match '^10\.') { return $true }
if ($ip -match '^172\.(1[6-9]|2[0-9]|3[0-1])\.') { return $true }
return $false
}
$vmIp = $null
try {
$vmAdapter = Get-VMNetworkAdapter -VMName 'dune-awakening' -ErrorAction SilentlyContinue
if ($vmAdapter -and $vmAdapter.IPAddresses) {
$validIps = $vmAdapter.IPAddresses | Where-Object { $_ -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' -and (Test-IsLocalIP $_) }
if ($validIps -and $validIps.Count -gt 0) {
$vmIp = @($validIps)[0]
Write-Host " Detected local Hyper-V VM IP: $vmIp" -ForegroundColor Green
}
}
} catch { }
if (-not $vmIp) {
$KnownHosts = Join-Path $env:USERPROFILE ".ssh\known_hosts"
if (Test-Path $KnownHosts) {
$content = Get-Content $KnownHosts
$localIps = @()
$publicIps = @()
foreach ($line in $content) {
if ($line -match '\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b') {
$ip = $matches[1]
if (Test-IsLocalIP $ip) {
$localIps += $ip
} else {
$publicIps += $ip
}
}
}
if ($localIps.Count -gt 0) {
$validLocal = $localIps | Where-Object { $_ -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' }
if ($validLocal) {
$vmIp = @($validLocal)[-1]
Write-Host " Detected local IP from SSH history: $vmIp" -ForegroundColor Green
}
} elseif ($publicIps.Count -gt 0) {
$validPublic = $publicIps | Where-Object { $_ -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' }
if ($validPublic) {
$vmIp = @($validPublic)[-1]
Write-Host " Detected IP from SSH history: $vmIp (verify this is your local VM)" -ForegroundColor Yellow
}
}
}
}
if ($vmIp) { $VmHost = $vmIp }
try {
$HostIp = (Invoke-WebRequest -Uri "https://api.ipify.org" -UseBasicParsing -TimeoutSec 5).Content.Trim()
} catch {
$localIps = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notlike 'Loopback*' -and $_.PrefixOrigin -ne 'WellKnown' } | Select-Object -ExpandProperty IPAddress
if ($localIps.Count -gt 0) { $HostIp = $localIps[0] }
}
Write-Host ""
Write-Host " Access Mode - Choose how you want to access the dashboard:" -ForegroundColor Cyan
Write-Host " Local only (n) - Access from this machine only (recommended)" -ForegroundColor DarkGray
Write-Host " Remote (y) - Access from other devices on your network" -ForegroundColor DarkGray
$val = Read-Host " Enable remote access? (n)"
$EnableRemote = ($val -eq 'y' -or $val -eq 'Y')
Write-Host ""
Write-Host " VM Host - IP of your game server (for SSH connection)" -ForegroundColor Cyan
if ($EnableRemote) {
Write-Host " Example: Your VM's external or LAN IP" -ForegroundColor DarkGray
} else {
Write-Host " Example: Your VM's local IP (e.g., 192.168.x.x, 10.x.x.x)" -ForegroundColor DarkGray
}
$vmHint = $VmHost
if ($vmIp -and $vmIp -match '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') {
$vmHint = "$VmHost (detected - press Enter to accept)"
}
$val = Read-Host " VM Host [$vmHint]"
if ($val) { $VmHost = $val }
if ($EnableRemote) {
Write-Host ""
Write-Host " This Machine's IP - used for SSL certificate (required for remote access)" -ForegroundColor Cyan
if ($HostIp) { $hostIpHint = "$HostIp (auto-detected)" } else { $hostIpHint = "Your machine's IP" }
$val = Read-Host " Host IP [$hostIpHint]"
if ($val) { $HostIp = $val }
elseif (-not $HostIp) { $HostIp = $null }
Write-Host ""
Write-Host " Domain Name (optional) - for a publicly trusted SSL certificate via Let's Encrypt." -ForegroundColor Cyan
Write-Host " This removes browser warnings for ALL visitors. Requires:" -ForegroundColor Cyan
Write-Host " - A domain (or subdomain) pointing to this machine's IP" -ForegroundColor Cyan
Write-Host " - Port 80 accessible from the internet" -ForegroundColor Cyan
$val = Read-Host " Domain (leave blank to use local CA instead)"
$DomainName = $null
if ($val -and $val -match '\S') { $DomainName = $val }
$LeEmail = $null
if ($DomainName) {
Write-Host ""
Write-Host " Email address is required by Let's Encrypt for expiry notifications." -ForegroundColor Cyan
$val = Read-Host " Email Address"
if ($val -and $val -match '\S') { $LeEmail = $val }
}
} else {
$DomainName = $null
$LeEmail = $null
$HostIp = $null
}
# Try SSH with the confirmed VM IP to auto-detect namespace
if ($FoundKey -and $VmHost -ne "YOUR_SERVER_IP") {
Write-Host " Testing SSH connection..." -ForegroundColor Yellow
Write-Host " (Fresh VMs may need time to initialize SSH keys - will retry up to 60s)" -ForegroundColor DarkGray
Write-Host ""
$sshOk = $false
for ($i = 0; $i -lt 12; $i++) {
try {
$testOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes dune@$VmHost "echo ok" 2>$null
$testExit = $LASTEXITCODE
if ($testOut -match "ok" -and $testExit -eq 0) {
$sshOk = $true
break
}
} catch {}
Write-Host " Attempt $($i+1)/12 - SSH not ready yet, waiting 5s..." -ForegroundColor DarkGray
Start-Sleep -Seconds 5
}
if ($sshOk) {
Write-Host " SSH connection OK" -ForegroundColor Green
try {
$nsOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes dune@$VmHost "sudo kubectl get namespaces -o name" 2>$null
} catch { $nsOut = $null }
if ($nsOut) {
foreach ($line in $nsOut -split "`n") {
$ns = $line -replace 'namespace/', ''
if ($ns -match '^funcom-seabass-') {
$K8sNamespace = $ns
Write-Host " Auto-detected namespace: $K8sNamespace" -ForegroundColor Green
break
}
}
}
} else {
Write-Host " SSH connection failed after 60s of retries" -ForegroundColor Yellow
Write-Host ""
Write-Host " This is normal on a fresh VM that hasn't finished initializing." -ForegroundColor Cyan
Write-Host " You can still continue setup - just enter the namespace manually below." -ForegroundColor Cyan
Write-Host ""
Write-Host " Once the VM is ready, copy your public key to enable SSH:" -ForegroundColor Cyan
Write-Host ""
$pubKeyContent = $null
try { $pubKeyContent = Get-Content "$FoundKey.pub" -ErrorAction SilentlyContinue } catch {}
if ($pubKeyContent) {
Write-Host " ssh dune@$VmHost 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo `"$pubKeyContent`" >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'" -ForegroundColor DarkGray
} else {
Write-Host " ssh dune@$VmHost 'mkdir -p ~/.ssh && chmod 700 ~/.ssh'" -ForegroundColor DarkGray
Write-Host " Then paste your public key into ~/.ssh/authorized_keys" -ForegroundColor DarkGray
}
Write-Host ""
}
}
}
# Interactive review/edit
Write-Host ""
Write-Host " Review settings (press Enter to accept, or type new value):" -ForegroundColor Cyan
Write-Host ""
Write-Host " VM Host: $VmHost (IP of your game server VM, used for SSH)"
if ($HostIp) { Write-Host " Host IP: $HostIp (This machine's external IP, used for SSL cert)" }
$val = Read-Host " Server User [$ServerUser] (SSH username for the VM)"
if ($val) { $ServerUser = $val }
Write-Host " SSH Key Path: $FoundKey (Path to your private SSH key)"
if (-not $K8sNamespace) {
Write-Host " [INFO] To find your namespace, run: ssh dune@YOUR_IP 'sudo kubectl get namespaces'" -ForegroundColor Cyan
$K8sHint = "funcom-seabass-<id> (Kubernetes cluster namespace)"
} else {
$K8sHint = "$K8sNamespace (Kubernetes cluster namespace)"
}
$val = Read-Host " K8s Namespace [$K8sHint]"
if ($val) { $K8sNamespace = $val }
elseif (-not $K8sNamespace) { $K8sNamespace = "" }
$val = Read-Host " Dashboard Port [$DashboardPort] (Local web access port)"
if ($val) { $DashboardPort = $val }
$val = Read-Host " DB Local Port [$DbPort] (Local database tunnel port)"
if ($val) { $DbPort = $val }
$val = Read-Host " Director Port [$DirectorPort] (Director API port)"
if ($val) { $DirectorPort = $val }
$val = Read-Host " FileBrowser Port [$FileBrowserPort] (File manager port)"
if ($val) { $FileBrowserPort = $val }
$val = Read-Host " Auth Username [$AuthUser] (Dashboard login name)"
if ($val) { $AuthUser = $val }
while ($true) {
$val = Read-Host " Auth Password (required)" -AsSecureString
$AuthPass = [System.Net.NetworkCredential]::new('', $val).Password
if (-not $AuthPass) {
Write-Host " [ERROR] Password is required. Setup cancelled." -ForegroundColor Red
return
}
$val2 = Read-Host " Confirm Password" -AsSecureString
$AuthPass2 = [System.Net.NetworkCredential]::new('', $val2).Password
if ($AuthPass -eq $AuthPass2) {
break
}
Write-Host " [ERROR] Passwords do not match. Please try again." -ForegroundColor Red
}
if (-not $QuickReconfig) {
# SSL certificate (Let's Encrypt or local CA)
Write-Host ""
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
$CertDir = Join-Path $ProjectRoot "ssl"
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
$LeConfigDir = Join-Path $ProjectRoot "certbot\config"
$LeWorkDir = Join-Path $ProjectRoot "certbot\work"
$LeLogsDir = Join-Path $ProjectRoot "certbot\logs"
$CaCertPath = Join-Path $CertDir "ca.pem"
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
$SslCertPath = Join-Path $CertDir "cert.pem"
$SslKeyPath = Join-Path $CertDir "key.pem"
$UseLetsEncrypt = $false
$LeCertPath = $null
$LeKeyPath = $null
$SslCert = "null"
$SslKey = "null"
if ($EnableRemote) {
if ($DomainName) {
Write-Host " Attempting Let's Encrypt certificate for $DomainName..." -ForegroundColor Yellow
$certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue
if (-not $certbotCmd) {
Write-Host " Installing certbot..." -ForegroundColor Yellow
try {
winget install --id Certbot.Certbot -e --accept-source-agreements --accept-package-agreements --silent 2>$null | Out-Null
$certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue
} catch {}
if (-not $certbotCmd) {
Write-Host " winget failed, trying pip..." -ForegroundColor Yellow
pip install certbot 2>$null | Out-Null
$certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue
}
if (-not $certbotCmd) {
$testCertbot = python -m certbot --version 2>$null
if ($LASTEXITCODE -eq 0) {
$certbotCmd = @{ Source = "python -m certbot" }
}
}
}
if ($certbotCmd) {
$httpRedirect = Get-NetTCPConnection -LocalPort 80 -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Listen' }
if ($httpRedirect) {
Write-Host " Temporarily stopping services on port 80 for certificate validation..." -ForegroundColor Yellow
}
$certbotUseModule = ($certbotCmd.Source -eq "python")
New-Item -ItemType Directory -Path $LeConfigDir -Force | Out-Null
New-Item -ItemType Directory -Path $LeWorkDir -Force | Out-Null
New-Item -ItemType Directory -Path $LeLogsDir -Force | Out-Null
$certbotDirArgs = @("--config-dir", $LeConfigDir, "--work-dir", $LeWorkDir, "--logs-dir", $LeLogsDir)
if ($certbotUseModule) {
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + $certbotDirArgs
if ($LeEmail) {
$certbotArgs += "--email"
$certbotArgs += $LeEmail
} else {
$certbotArgs += "--register-unsafely-without-email"
}
$certbotResult = Start-Process python -ArgumentList $certbotArgs -Wait -NoNewWindow -PassThru -RedirectStandardOutput "$env:TEMP\certbot-out.txt"
} else {
$certbotArgs = @(
"certonly", "--standalone",
"-d", $DomainName,
"--non-interactive",
"--agree-tos"
) + $certbotDirArgs
if ($LeEmail) {
$certbotArgs += "--email"
$certbotArgs += $LeEmail
} else {
$certbotArgs += "--register-unsafely-without-email"
}
$certbotResult = Start-Process certbot -ArgumentList $certbotArgs -Wait -NoNewWindow -PassThru -RedirectStandardOutput "$env:TEMP\certbot-out.txt"
}
$certbotOutput = Get-Content "$env:TEMP\certbot-out.txt" -ErrorAction SilentlyContinue
if ($certbotResult.ExitCode -eq 0) {
$UseLetsEncrypt = $true
$LeLiveDir = Join-Path $LeConfigDir "live\$DomainName"
$LeCertPath = Join-Path $LeLiveDir "fullchain.pem"
$LeKeyPath = Join-Path $LeLiveDir "privkey.pem"
if (Test-Path $LeCertPath) {
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
Write-Host " Certificate for $DomainName is publicly trusted." -ForegroundColor Green
} else {
Write-Host " [WARN] Let's Encrypt succeeded but cert files not found at expected path." -ForegroundColor Yellow
Write-Host " Falling back to local CA." -ForegroundColor Yellow
$UseLetsEncrypt = $false
}
} else {
Write-Host " [WARN] Let's Encrypt certificate failed." -ForegroundColor Yellow
if ($certbotOutput) { $certbotOutput | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow } }
Write-Host " Falling back to local CA certificate." -ForegroundColor Yellow
Write-Host " To retry, run setup again after installing certbot: winget install Certbot.Certbot" -ForegroundColor Yellow
}
} else {
Write-Host " [WARN] certbot not available. Falling back to local CA certificate." -ForegroundColor Yellow
Write-Host " To install certbot later, run: winget install Certbot.Certbot" -ForegroundColor Yellow
Write-Host " Then re-run setup to get a Let's Encrypt certificate." -ForegroundColor Yellow
}
}
if (-not $UseLetsEncrypt) {
$CaCertPathPy = $CaCertPath -replace '\\', '/'
$CaKeyPathPy = $CaKeyPath -replace '\\', '/'
$SslCertPathPy = $SslCertPath -replace '\\', '/'
$SslKeyPathPy = $SslKeyPath -replace '\\', '/'
$SanIps = @('127.0.0.1')
if ($VmHost -ne "YOUR_SERVER_IP") { $SanIps += $VmHost }
if ($HostIp -and $HostIp -notin $SanIps) { $SanIps += $HostIp }
if (-not (Test-Path $CaCertPath) -or -not (Test-Path $CaKeyPath)) {
Write-Host " Generating local CA..." -ForegroundColor Yellow
python -c "from app.utils.ssl import generate_ca; generate_ca('$CaCertPathPy', '$CaKeyPathPy')"
}
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
$SanDnsArray = "['localhost'"
if ($DomainName) { $SanDnsArray += ", '" + $DomainName + "'" }
$SanDnsArray += "]"
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=$SanDnsArray)"
$SslCert = "'$SslCertPath'"
$SslKey = "'$SslKeyPath'"
Write-Host ""
Write-Host " A local CA certificate was generated (Let's Encrypt was not used)." -ForegroundColor Cyan
Write-Host " Installing it into the Trusted Root store will remove browser warnings on THIS machine only." -ForegroundColor Cyan
Write-Host " Visitors from other machines will still see a warning unless they also install the CA cert." -ForegroundColor Cyan
Write-Host " To get a publicly trusted certificate, re-run setup and provide a domain name." -ForegroundColor Cyan
Write-Host ""
$InstallCa = Read-Host " Install CA certificate now? Requires Administrator (y/N)"
if ($InstallCa -eq 'y' -or $InstallCa -eq 'Y') {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host ""
Write-Host " [WARN] Not running as Administrator." -ForegroundColor Yellow
Write-Host " Starting a new elevated PowerShell window to install the CA cert..." -ForegroundColor Yellow
Write-Host ""
$elevatedScript = "certutil -addstore -f 'Root' '$CaCertPath'; Write-Host ''; Read-Host 'Press Enter to close'"
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $elevatedScript -Verb RunAs -Wait
Write-Host " CA certificate installation complete." -ForegroundColor Green
} else {
certutil -addstore -f "Root" $CaCertPath
if ($LASTEXITCODE -eq 0) {
Write-Host " CA certificate installed to Trusted Root Certification Authorities." -ForegroundColor Green
} else {
Write-Host " [WARN] certutil failed. Try running setup as Administrator." -ForegroundColor Yellow
}
}
Write-Host " Restart your browser for the change to take effect." -ForegroundColor Cyan
} else {
Write-Host " Skipped. You can install it later from the launcher menu (option 4)." -ForegroundColor Yellow
}
} else {
$SslCert = "'$LeCertPath'"
$SslKey = "'$LeKeyPath'"
}
}
if ($EnableRemote) {
$DashHost = "0.0.0.0"
} else {
$DashHost = "127.0.0.1"
}
$HttpRedirect = $false
$HttpRedirectPort = 80
if ($EnableRemote -and ($SslCert -ne "null") -and ($SslKey -ne "null")) {
Write-Host ""
Write-Host " Optional HTTP to HTTPS redirect:" -ForegroundColor Cyan
Write-Host " - Not required if you visit https://HOST:$DashboardPort directly." -ForegroundColor Cyan
Write-Host " - Useful if you want http://HOST to redirect automatically." -ForegroundColor Cyan
Write-Host " - Requires TCP port 80 to be free and forwarded/open." -ForegroundColor Cyan
$RedirectAnswer = Read-Host " Enable HTTP redirect on port 80? (y/N)"
$HttpRedirect = ($RedirectAnswer -eq 'y' -or $RedirectAnswer -eq 'Y')
}
# Firewall rules
Write-Host ""
if ($EnableRemote) {
$FirewallPorts = @($DashboardPort)
if ($HttpRedirect) { $FirewallPorts = @(80) + $FirewallPorts }
$FirewallPortList = ($FirewallPorts -join ',')
Write-Host " Windows Firewall needs to allow incoming TCP port(s): $FirewallPortList" -ForegroundColor Cyan
Write-Host " This requires Administrator privileges." -ForegroundColor Cyan
Write-Host ""
} else {
$FirewallPorts = @()
$FirewallPortList = ""
Write-Host " Skipping Windows Firewall rules because remote access is disabled." -ForegroundColor Cyan
}
Write-Host ""
if ($EnableRemote) {
$SetupFirewall = Read-Host " Create firewall rules? (Y/n)"
} else {
$SetupFirewall = "n"
}
if ($SetupFirewall -eq 'n' -or $SetupFirewall -eq 'N') {
if ($EnableRemote) { Write-Host " Skipped. Remote access may be blocked by firewall." -ForegroundColor Yellow }
} else {
$fwRuleName = "DuneDashboard"
$fwExists = $null
try { $fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue } catch {}
if ($fwExists) {
Write-Host " Firewall rule already exists." -ForegroundColor Green
} else {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host " Starting elevated PowerShell to add firewall rules..." -ForegroundColor Yellow
$fwScript = "New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort $FirewallPortList; Write-Host ''; Read-Host 'Press Enter to close'"
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $fwScript -Verb RunAs -Wait
Write-Host " Firewall rules added." -ForegroundColor Green
} else {
New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort $FirewallPorts
Write-Host " Firewall rules added for TCP port(s): $FirewallPortList." -ForegroundColor Green
}
}
}
# Let's Encrypt auto-renewal
if ($UseLetsEncrypt) {
Write-Host ""
Write-Host " Setting up Let's Encrypt auto-renewal..." -ForegroundColor Yellow
$taskName = "DuneDashboard-LeRenewal"
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($existingTask) {
Write-Host " Renewal task already exists." -ForegroundColor Green
} else {
# Resolve certbot.exe path — SYSTEM account may not have it in PATH
$certbotCandidates = @(
"$env:ProgramFiles\Certbot\bin\certbot.exe",
"$env:LOCALAPPDATA\Programs\Python\Python312\Scripts\certbot.exe",
"$env:LOCALAPPDATA\Programs\Python\Python311\Scripts\certbot.exe",
"$env:LOCALAPPDATA\Programs\Python\Python310\Scripts\certbot.exe",
"$env:ProgramFiles\Python312\Scripts\certbot.exe",
"$env:ProgramFiles\Python311\Scripts\certbot.exe",
"$env:ProgramFiles\Python310\Scripts\certbot.exe"
)
$certbotPath = $null
foreach ($path in $certbotCandidates) {
if (Test-Path $path) {
$certbotPath = $path
break
}
}
if (-not $certbotPath) {
$certbotPath = (Get-Command "certbot" -ErrorAction SilentlyContinue).Source
}
if (-not $certbotPath) {
$certbotPath = "certbot"
}
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet --config-dir `"$LeConfigDir`" --work-dir `"$LeWorkDir`" --logs-dir `"$LeLogsDir`""
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $renewAction -Trigger $renewTrigger -Settings $renewSettings -Principal $renewPrincipal -Description "Auto-renew Let's Encrypt certificate for Dune Dashboard" -ErrorAction SilentlyContinue | Out-Null
Write-Host " Auto-renewal scheduled (daily at 2 AM). Certificates renew automatically." -ForegroundColor Green
}
}
}
# Firewall security hardening
Write-Host ""
Write-Host "[SECURITY] Firewall Hardening" -ForegroundColor Cyan
Write-Host ""
Write-Host " Your game server has services exposed to the internet without authentication." -ForegroundColor Yellow
Write-Host " This is a SECURITY RISK - these services are vulnerable to automated attacks." -ForegroundColor Yellow
Write-Host ""
Write-Host " Recommended: Block these ports so only localhost/VPN can reach them:" -ForegroundColor Cyan
Write-Host ""
Write-Host " [1] File Browser (port 18888) - VULNERABLE (no auth - exposes server files)" -ForegroundColor Yellow
Write-Host " [2] Battlegroup Director (port 31820) - VULNERABLE (no auth - exposes server API)" -ForegroundColor Yellow
Write-Host ""
Write-Host " You can change these anytime from the Server page in the dashboard." -ForegroundColor Cyan
Write-Host ""
$val = Read-Host " Block File Browser (18888)? (Y/n)"
$BlockFileBrowser = -not ($val -eq 'n' -or $val -eq 'N')
if ($BlockFileBrowser) { Write-Host " Will block port 18888 (File Browser)" -ForegroundColor Green }
else { Write-Host " Skipped - port 18888 will remain open to the internet" -ForegroundColor Yellow }
Write-Host ""
$val = Read-Host " Block Battlegroup Director (31820)? (Y/n)"
$BlockDirector = -not ($val -eq 'n' -or $val -eq 'N')
if ($BlockDirector) { Write-Host " Will block port 31820 (Director)" -ForegroundColor Green }
else { Write-Host " Skipped - port 31820 will remain open to the internet" -ForegroundColor Yellow }
# Save settings
Write-Host ""
Write-Host "[5/6] Saving settings..." -ForegroundColor Yellow
$secret = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_})
Write-Host " Hashing password with Argon2..." -ForegroundColor Yellow
$pwScript = @"
import sys
from argon2 import PasswordHasher
ph = PasswordHasher()
print(ph.hash(sys.argv[1]))
"@
$pwScript | Out-File -FilePath "$env:TEMP\hash_pw.py" -Encoding utf8 -Force
$hashResult = python "$env:TEMP\hash_pw.py" $AuthPass 2>$null
Remove-Item "$env:TEMP\hash_pw.py" -Force -ErrorAction SilentlyContinue
if ($hashResult -and $hashResult -match '^\$argon2') {
$AuthHash = $hashResult.Trim()
Write-Host " Password hashed successfully." -ForegroundColor Green
} else {
Write-Host " [ERROR] Failed to hash password. Argon2 may not be installed." -ForegroundColor Red
Write-Host " Run: pip install argon2-cffi" -ForegroundColor Yellow
return
}
$sshKeyPath = if ($FoundKey) { $FoundKey -replace '\\', '\\' } else { "null" }
$leDomain = if ($DomainName) { $DomainName } else { "null" }
$leEmail = if ($LeEmail) { $LeEmail } else { "null" }
$vmLocalIp = if ($vmIp) { $vmIp } else { "null" }
$settingsContent = @"
server:
host: '$VmHost'
local_ip: '$vmLocalIp'
user: $ServerUser
ssh_key: '$sshKeyPath'
dashboard:
host: $DashHost
port: $DashboardPort
debug: false
secret_key: $secret
ssl_cert: $SslCert
ssl_key: $SslKey
ssl_domain: $leDomain
ssl_email: $leEmail
http_redirect: $HttpRedirect
http_redirect_port: $HttpRedirectPort
database:
host: $DbHost
port: $DbPort
user: postgres
password: postgres
name: dune
schema: dune
min_connections: 2
max_connections: 10
kubernetes:
namespace: '$K8sNamespace'
battlegroup_script: /home/dune/.dune/bin/battlegroup
director:
port: $DirectorPort
filebrowser:
port: $FileBrowserPort
firewall:
block_filebrowser: $BlockFileBrowser
block_director: $BlockDirector
cache:
chat_pod_ttl: 60
chat_messages_ttl: 10
static_data_ttl: 300
auth:
enabled: true
username: $AuthUser
password_hash: '$AuthHash'
logging:
level: INFO
file: logs/dashboard.log
max_bytes: 10485760
backup_count: 5
"@
[System.IO.File]::WriteAllText((Join-Path $ProjectRoot "settings.yaml"), $settingsContent, [System.Text.UTF8Encoding]::new($false))
Write-Host " Settings saved to settings.yaml" -ForegroundColor Green
New-Item -ItemType Directory -Path (Join-Path $ProjectRoot "logs") -Force | Out-Null
Write-Host ""
Write-Host "[6/6] Verifying setup..." -ForegroundColor Yellow
$verifyResult = python -W ignore -c "from app.config import load_settings; s = load_settings(); print('OK - settings loaded')" 2>$null
if ($verifyResult -match "OK") {
Write-Host " $verifyResult" -ForegroundColor Green
} else {
Write-Host " [WARN] Verification skipped." -ForegroundColor Yellow
}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Setup Complete!" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
# Check if SSH key is valid for the server
$SshValid = $false
if ($FoundKey -and (Test-Path $FoundKey) -and $VmHost -ne "YOUR_SERVER_IP") {
$testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${VmHost}" "echo ok" 2>$null
$SshValid = ($testOut -eq "ok")
}
if (-not $SshValid) {
if ($VmHost -eq "YOUR_SERVER_IP") {
Write-Host " Remember to edit settings.yaml with your server IP before starting." -ForegroundColor Yellow
} else {
Write-Host " SSH key is not configured or failed to connect." -ForegroundColor Yellow
}
Write-Host ""
Write-Host " Then start the dashboard with:" -ForegroundColor Yellow
Write-Host ""
Write-Host " .\launcher.ps1 (option 1)" -ForegroundColor Cyan
} else {
Write-Host " SSH connection verified." -ForegroundColor Green
$portsToBlock = @()
if ($BlockFileBrowser) { $portsToBlock += 18888 }
if ($BlockDirector) { $portsToBlock += 31820 }
if ($portsToBlock.Count -gt 0) {
Write-Host ""
Write-Host " Applying firewall rules to block ports: $($portsToBlock -join ', ')..." -ForegroundColor Yellow
$tmpFwScript = Join-Path $env:TEMP ([System.IO.Path]::GetRandomFileName() + ".sh")
$fwContent = "for PORT in $($portsToBlock -join ' '); do`n"
$fwContent += " if iptables -t mangle -C PREROUTING -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT 2>/dev/null; then`n"
$fwContent += " echo 'Port `$PORT already blocked'`n"
$fwContent += " else`n"
$fwContent += " iptables -I INPUT 1 -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT`n"
$fwContent += " iptables -I INPUT 2 -p tcp --dport `$PORT -j DROP`n"
$fwContent += " iptables -I FORWARD 1 -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT`n"
$fwContent += " iptables -I FORWARD 2 -p tcp --dport `$PORT -j DROP`n"
$fwContent += " iptables -t mangle -I PREROUTING 1 -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT`n"
$fwContent += " iptables -t mangle -I PREROUTING 2 -p tcp --dport `$PORT -j DROP`n"
$fwContent += " echo 'Port `$PORT blocked'`n"
$fwContent += " fi`n"
$fwContent += "done`n"
$fwContent += "echo 'FIREWALL_DONE'`n"
$fwContent | Out-File -FilePath $tmpFwScript -Encoding ascii -NoNewline -Force
$bytes = [System.IO.File]::ReadAllBytes($tmpFwScript)
Remove-Item $tmpFwScript -Force -ErrorAction SilentlyContinue
$b64 = [Convert]::ToBase64String($bytes)
$fwOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 "${ServerUser}@${VmHost}" "echo '$b64' | base64 -d > /tmp/fw.sh && sudo bash /tmp/fw.sh && rm /tmp/fw.sh" 2>&1
if ($fwOut -match "FIREWALL_DONE") {
Write-Host " Firewall rules applied successfully!" -ForegroundColor Green
} else {
Write-Host " [WARN] Firewall rules may not have applied correctly." -ForegroundColor Yellow
if ($fwOut.Length -gt 300) {
Write-Host " Output: $($fwOut.Substring(0, 300))" -ForegroundColor Yellow
} else {
Write-Host " Output: $fwOut" -ForegroundColor Yellow
}
}
}
Write-Host ""
Write-Host " Start the dashboard with:" -ForegroundColor Yellow
Write-Host ""
Write-Host " .\launcher.ps1 (option 1)" -ForegroundColor Cyan
}
Write-Host ""
Write-Host " Press Enter to return to the main menu..." -ForegroundColor Cyan
Read-Host " "
}
function Start-Dashboard {
param(
[switch]$PreserveDebug
)
Write-Host ""
Write-Host " Starting dashboard..." -ForegroundColor Yellow
Write-Host ""
# Check Python
if (-not (Test-Python)) {
Write-Host " Cannot start without Python. Please install Python 3.8+ first." -ForegroundColor Red
return
}
# Check dependencies
Test-Dependencies | Out-Null
# Check settings
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host ""
Write-Host " [ERROR] settings.yaml not found. You need to run setup first." -ForegroundColor Red
Write-Host ""
Write-Host " Run setup to configure the dashboard before starting it." -ForegroundColor Yellow
return
}
# Read settings
$settingsJson = python -c "import yaml, json, sys, os; path = sys.argv[1]; d = yaml.safe_load(open(path, encoding='utf-8-sig')) or {} if os.path.exists(path) else {}; print(json.dumps(d))" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host " [ERROR] Failed to read settings.yaml" -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
# Ensure debug logging is disabled for normal start (unless PreserveDebug is set)
if (-not $PreserveDebug) {
$needsSave = $false
if ($settings.logging) {
if ($settings.logging.debug_enabled -eq $true) {
$settings.logging.debug_enabled = $false
$settings.logging.level = "INFO"
$needsSave = $true
}
}
if ($needsSave) {
$settingsJson = $settings | ConvertTo-Json -Depth 10
$settingsJson | python "$env:TEMP\update_settings_debug.py" $settingsFile 2>$null
}
}
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$LocalPort = [int]$settings.database.port
$Namespace = $settings.kubernetes.namespace
$DashboardPort = [int]$settings.dashboard.port
$DirectorPort = [int]$settings.director.port
# Register sensitive values for log sanitization
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
Register-SensitiveValue -Key "Namespace" -Value $Namespace
Register-SensitiveValue -Key "DBPassword" -Value $settings.database.password
Register-SensitiveValue -Key "DBUser" -Value $settings.database.user
Register-SensitiveValue -Key "DashboardSecret" -Value $settings.dashboard.secret_key
Register-SensitiveValue -Key "AuthSecret" -Value $settings.auth.secret_key
Register-SensitiveValue -Key "DirectorToken" -Value $settings.director.token
# Find SSH key
function Test-SshKeyForStart($keyPath, $targetServer) {
if (-not (Test-Path $keyPath)) { return $false }
try {
$out = ssh -i $keyPath -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
return $out -eq "ok"
} catch { return $false }
}
$SSHKeySrc = $settings.server.ssh_key
$LocalKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
$ParentKey = Join-Path (Split-Path $ProjectRoot) "internal-scripts\ssh\sshKey"
if ($SSHKeySrc -and $SSHKeySrc -ne 'null' -and -not [string]::IsNullOrEmpty($SSHKeySrc)) {
if (Test-SshKeyForStart $SSHKeySrc ($SSHUser + '@' + $ServerHost)) {
Register-SensitiveValue -Key "SSHKeyPath" -Value $SSHKeySrc
Write-Host " SSH Key: Using key from settings.yaml" -ForegroundColor Green
} else {
Write-Host " SSH Key: Key in settings.yaml failed, searching..." -ForegroundColor Yellow
$SSHKeySrc = $null
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc) -or -not (Test-SshKeyForStart $SSHKeySrc ($SSHUser + '@' + $ServerHost))) {
$keyPaths = @(
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
$LocalKey,
$ParentKey,
"$env:USERPROFILE\.ssh\id_ed25519",
"$env:USERPROFILE\.ssh\id_rsa",
"$env:USERPROFILE\.ssh\id_ecdsa",
"$env:TEMP\dune-tunnel-key",
"$env:TEMP\dune-awakening-server-sshKey"
)
foreach ($kp in $keyPaths) {
if ($kp -ne $SSHKeySrc -and (Test-Path $kp)) {
if (Test-SshKeyForStart $kp ($SSHUser + '@' + $ServerHost)) {
$SSHKeySrc = $kp
Register-SensitiveValue -Key "SSHKeyPath" -Value $kp
Write-Host " SSH Key: Found working key at $kp" -ForegroundColor Green
break
}
}
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc)) {
Write-Host ""
Write-Host " [ERROR] No working SSH key found." -ForegroundColor Red
Write-Host ""
Write-Host " The dashboard needs an SSH key to connect to your game server." -ForegroundColor Yellow
Write-Host " Place a valid key in one of these locations:" -ForegroundColor Yellow
Write-Host " - $ProjectRoot\internal-scripts\ssh\sshKey" -ForegroundColor DarkGray
Write-Host " - %LOCALAPPDATA%\DuneAwakeningServer\sshKey" -ForegroundColor DarkGray
Write-Host " - %USERPROFILE%\.ssh\id_ed25519" -ForegroundColor DarkGray
Write-Host ""
Write-Host " Or update the ssh_key path in settings.yaml." -ForegroundColor Yellow
return
}
# Copy SSH key to temp with restricted permissions
if ($SSHKeySrc -ne $LocalKey -and (Test-Path $LocalKey) -and (Get-Item $LocalKey).Length -eq 0) {
Copy-Item $SSHKeySrc $LocalKey -Force
Write-Host " Updated internal key file" -ForegroundColor Green
}
$SSHKey = "$env:TEMP\dune-tunnel-key"
$ResolvedSrc = [System.IO.Path]::GetFullPath($SSHKeySrc)
$ResolvedDest = [System.IO.Path]::GetFullPath($SSHKey)
if ($ResolvedSrc -ne $ResolvedDest) {
Copy-Item $SSHKeySrc $SSHKey -Force
}
try {
$acl = Get-Acl $SSHKey -ErrorAction SilentlyContinue
if ($acl) {
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path $SSHKey -AclObject $acl -ErrorAction SilentlyContinue
}
} catch {}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Awakening Dashboard" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Sep -Title "Dashboard Launch" -Category "general"
Write-Log -Message "Server: $ServerHost, User: $SSHUser" -Category "general"
Write-Log -Message "Ports: DB=$LocalPort, Director=$DirectorPort, Dashboard=$DashboardPort" -Category "general"
Write-Log -Message "Namespace: $Namespace" -Category "k8s"
# Kill existing SSH tunnels on the DB/Director ports
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort and $DirectorPort" -Category "ssh"
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Start-Sleep 1
# [1/4] SSH Tunnel
Write-Step -Name "SSH Tunnel" -Category "ssh"
Write-Host "[1/4] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
Write-Log -Message "Starting SSH tunnel to ${SSHUser}@${ServerHost}" -Category "ssh"
$sshArgs = @(
"-i", $SSHKey,
"-o", "StrictHostKeyChecking=accept-new",
"-o", "ServerAliveInterval=30",
"-o", "ServerAliveCountMax=3",
"-L", "${LocalPort}:localhost:${LocalPort}",
"-L", "${DirectorPort}:localhost:${DirectorPort}",
"-N", "${SSHUser}@${ServerHost}"
)
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
$connected = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
if ($sshTunnel.HasExited) {
Write-Host "[ERROR] SSH tunnel exited (code: $($sshTunnel.ExitCode))" -ForegroundColor Red
Write-Log -Message "SSH tunnel exited unexpectedly (code: $($sshTunnel.ExitCode))" -Level "ERROR" -Category "ssh"
Write-Host ""
Write-Host " The SSH tunnel could not connect to your game server." -ForegroundColor Yellow
Write-Host ""
Write-Host " Troubleshooting:" -ForegroundColor Cyan
Write-Host " 1. Make sure the game server VM is running" -ForegroundColor White
Write-Host " 2. Check that the server IP in settings.yaml is correct: $ServerHost" -ForegroundColor White
Write-Host " 3. Verify your SSH key is authorized on the VM" -ForegroundColor White
Write-Host " 4. Try connecting manually: ssh -i $SSHKey ${SSHUser}@${ServerHost}" -ForegroundColor White
Write-Host ""
return
}
try {
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("127.0.0.1", $LocalPort)
$tcp.Close()
$connected = $true
break
} catch {}
}
if (-not $connected) {
Write-Host "[ERROR] SSH tunnel did not connect within 30 seconds" -ForegroundColor Red
Write-Log -Message "SSH tunnel failed to connect within 30 seconds" -Level "ERROR" -Category "ssh"
Write-Host ""
Write-Host " The SSH tunnel could not establish a connection." -ForegroundColor Yellow
Write-Host ""
Write-Host " Troubleshooting:" -ForegroundColor Cyan
Write-Host " 1. Check that your game server VM is running" -ForegroundColor White
Write-Host " 2. Verify network connectivity: ping $ServerHost" -ForegroundColor White
Write-Host " 3. Check if port $LocalPort is blocked by a firewall" -ForegroundColor White
Write-Host " 4. Try connecting manually: ssh -i $SSHKey ${SSHUser}@${ServerHost}" -ForegroundColor White
Write-Host ""
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director)" -ForegroundColor Green
Write-Log -Message "SSH tunnel connected successfully" -Category "ssh"
# [2/4] DB Port-Forward
Write-Host "[2/4] Starting DB port-forward on VM..." -ForegroundColor Yellow
Write-Log -Message "Starting DB port-forward in namespace: $Namespace" -Category "k8s"
if (-not $Namespace -or $Namespace -eq '') {
Write-Host "[ERROR] Kubernetes namespace is empty." -ForegroundColor Red
Write-Log -Message "Kubernetes namespace is empty, cannot proceed" -Level "ERROR" -Category "k8s"
Write-Host ""
Write-Host " The dashboard needs to know your Kubernetes namespace to connect to the database." -ForegroundColor Yellow
Write-Host ""
Write-Host " To find your namespace:" -ForegroundColor Cyan
Write-Host " 1. SSH into your game server: ssh -i $SSHKey ${SSHUser}@${ServerHost}" -ForegroundColor White
Write-Host " 2. Run: sudo kubectl get namespaces" -ForegroundColor White
Write-Host " 3. Look for a namespace starting with 'funcom-seabass-'" -ForegroundColor White
Write-Host " 4. Edit settings.yaml and set kubernetes.namespace to that value" -ForegroundColor White
Write-Host ""
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
$DBService = "${Namespace}-db-dbdepl-svc"
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheck) {
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
if ($dbSvc) {
$DBService = $dbSvc -replace 'service/', ''
Write-Host " Found DB service: $DBService" -ForegroundColor Green
Write-Log -Message "Auto-detected DB service: $DBService" -Category "k8s"
}
}
$RemotePort = 15432
Write-Log -Message "Starting port-forward: ${LocalPort}:${RemotePort} on service $DBService" -Category "database"
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
Start-Sleep -Seconds 2
$bgdSvc = "${Namespace}-bgd-svc"
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheckBgd) {
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
}
# Check if BGD deployment is running, scale up if needed
$bgdDeploy = "${Namespace}-bgd-deploy"
Write-Log -Message "Checking BGD deployment status: $bgdDeploy" -Category "k8s"
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
Write-Log -Message "BGD deployment scaled down, scaling to 1 replica" -Category "k8s"
$scaleOut = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
Write-Host " Waiting for BGD pod to be ready..." -ForegroundColor Yellow
Start-Sleep -Seconds 15
}
$directorRemotePort = 11717
Write-Log -Message "Starting director port-forward: ${DirectorPort}:${directorRemotePort} on service $bgdSvc" -Category "k8s"
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
Start-Sleep -Seconds 3
# [3/4] Database Check
Write-Host "[3/4] Checking database..." -ForegroundColor Yellow
$dbTest = $false
$dbScript = Join-Path $ProjectRoot "scripts\db_check.py"
for ($i = 0; $i -lt 15; $i++) {
try {
$result = python $dbScript $LocalPort 2>$null
if ($result -match 'ok') { $dbTest = $true; break }
} catch {}
Start-Sleep -Seconds 1
}
if (-not $dbTest) {
Write-Host "[ERROR] Database connection failed." -ForegroundColor Red
Write-Host ""
Write-Host " The dashboard could not connect to the game server's database." -ForegroundColor Yellow
Write-Host ""
Write-Host " Troubleshooting:" -ForegroundColor Cyan
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
$pfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/pf.log" 2>$null
if ($pfLog) { Write-Host " $pfLog" -ForegroundColor Red }
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
Write-Host ""
Write-Host " 2. Verify the DB service exists on the VM:" -ForegroundColor White
Write-Host " ssh -i $SSHKey ${SSHUser}@${ServerHost} 'sudo kubectl get svc -n $Namespace'" -ForegroundColor DarkGray
Write-Host ""
Write-Host " 3. Check that the database port in settings.yaml is correct: $LocalPort" -ForegroundColor White
Write-Host ""
Write-Host " 4. The database service name should be: $DBService" -ForegroundColor White
Write-Host " If it's different, the port-forward may be targeting the wrong service." -ForegroundColor White
Write-Host ""
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] Database connected" -ForegroundColor Green
# [3/4] Director Check
Write-Host "[3/4] Checking director connection..." -ForegroundColor Yellow
$directorTest = $false
for ($i = 0; $i -lt 15; $i++) {
try {
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("127.0.0.1", $DirectorPort)
$tcp.Close()
$directorTest = $true
break
} catch {}
Start-Sleep -Seconds 1
}
if (-not $directorTest) {
Write-Host "[WARN] Director port-forward not responding on localhost:$DirectorPort" -ForegroundColor Yellow
Write-Host " The Director tab may not work until the port-forward is active." -ForegroundColor Yellow
Write-Host ""
Write-Host " Troubleshooting:" -ForegroundColor Cyan
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
$directorPfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/director_pf.log" 2>$null
if ($directorPfLog) { Write-Host " $directorPfLog" -ForegroundColor Red }
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
Write-Host ""
Write-Host " 2. Verify the BGD service exists on the VM:" -ForegroundColor White
Write-Host " ssh -i $SSHKey ${SSHUser}@${ServerHost} 'sudo kubectl get svc -n $Namespace'" -ForegroundColor DarkGray
Write-Host ""
} else {
Write-Host "[OK] Director port-forward connected" -ForegroundColor Green
}
# [4/4] Firewall check for remote access
$fwRuleName = "DuneDashboard"
$fwExists = $null
try { $fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue } catch {}
$remoteDashboard = "$($settings.dashboard.host)" -eq "0.0.0.0"
if ($remoteDashboard -and -not $fwExists) {
Write-Host "[WARN] No Windows Firewall rule found for remote access." -ForegroundColor Yellow
Write-Host " Other devices on your network may not be able to reach the dashboard." -ForegroundColor Yellow
Write-Host ""
Write-Host " To allow remote access, you need to:" -ForegroundColor Cyan
Write-Host " 1. Open Windows Firewall for port $DashboardPort (TCP)" -ForegroundColor White
Write-Host " 2. If behind a router, set up port forwarding for port $DashboardPort" -ForegroundColor White
Write-Host ""
Write-Host " Quick firewall fix (run as Administrator):" -ForegroundColor White
Write-Host " New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort $DashboardPort" -ForegroundColor DarkGray
Write-Host ""
$redirectEnabled = $settings.dashboard.http_redirect -eq $true
if ($redirectEnabled) {
$redirectPort = if ($settings.dashboard.http_redirect_port) { $settings.dashboard.http_redirect_port } else { 80 }
Write-Host " Ports needed: $redirectPort (optional HTTP redirect), $DashboardPort (dashboard)" -ForegroundColor Yellow
} else {
Write-Host " Port needed: $DashboardPort (dashboard)" -ForegroundColor Yellow
}
Write-Host ""
$SetupFirewall = Read-Host " Create firewall rules now? Requires Administrator (Y/n)"
if ($SetupFirewall -ne 'n' -and $SetupFirewall -ne 'N') {
$firewallPorts = @($DashboardPort)
if ($redirectEnabled) { $firewallPorts = @($redirectPort) + $firewallPorts }
$firewallPortList = ($firewallPorts -join ',')
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host " Starting elevated PowerShell to add firewall rules..." -ForegroundColor Yellow
$fwScript = "New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort $firewallPortList; Write-Host ''; Read-Host 'Press Enter to close'"
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $fwScript -Verb RunAs -Wait
Write-Host "[OK] Firewall rules added." -ForegroundColor Green
} else {
New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort $firewallPorts
Write-Host "[OK] Firewall rules added for port(s): $firewallPortList." -ForegroundColor Green
}
} else {
Write-Host " Skipped. External access may be blocked by Windows Firewall." -ForegroundColor Yellow
}
Write-Host ""
}
# [4/4] Start Dashboard
Write-Host "[4/4] Starting dashboard..." -ForegroundColor Yellow
Write-Host ""
# Determine access URLs
$protocol = "http"
$sslCert = $settings.dashboard.ssl_cert
$sslKey = $settings.dashboard.ssl_key
if ($sslCert -and $sslKey -and $sslCert -ne 'null' -and $sslKey -ne 'null') {
if ((Test-Path $sslCert) -and (Test-Path $sslKey)) {
$protocol = "https"
}
}
$dashHost = $settings.dashboard.host
if ($dashHost -eq '0.0.0.0') {
Write-Host " Dashboard is accessible at:" -ForegroundColor Green
Write-Host " Local: ${protocol}://localhost:$DashboardPort" -ForegroundColor Cyan
Write-Host " Local: ${protocol}://127.0.0.1:$DashboardPort" -ForegroundColor Cyan
Write-Host " Network: ${protocol}://<this-computer-ip>:$DashboardPort" -ForegroundColor Cyan
Write-Host " Internet: ${protocol}://<your-public-ip>:$DashboardPort" -ForegroundColor Cyan
} else {
Write-Host " ${protocol}://$dashHost`:$DashboardPort" -ForegroundColor Cyan
}
Write-Host ""
Write-Host " Press Ctrl+C to stop the dashboard." -ForegroundColor DarkGray
Write-Host ""
Set-Location -LiteralPath $ProjectRoot
python run.py
Write-Host ""
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k 15433/tcp 32479/tcp 2>/dev/null"'
cmd /c $pkillCmd 2>$null
}
function Start-DashboardDebug {
Write-Host ""
Write-Host " ============================================================" -ForegroundColor Magenta
Write-Host " Starting Dashboard with DEBUG LOGGING enabled" -ForegroundColor Magenta
Write-Host " ============================================================" -ForegroundColor Magenta
Write-Host ""
Write-Host " ⚠️ WARNING: Debug logging can significantly impact performance!" -ForegroundColor Yellow
Write-Host " - Logs every HTTP request/response with full headers" -ForegroundColor Yellow
Write-Host " - Logs all SSH commands and results" -ForegroundColor Yellow
Write-Host " - Logs all database queries" -ForegroundColor Yellow
Write-Host " - Logs all Kubernetes operations" -ForegroundColor Yellow
Write-Host " - Only use this when troubleshooting, not for regular use" -ForegroundColor Yellow
Write-Host ""
$continue = Read-Host " Continue with debug mode? (y/N)"
if ($continue -ne 'y' -and $continue -ne 'Y') {
Write-Host " Cancelled." -ForegroundColor Cyan
return
}
# Check Python
if (-not (Test-Python)) {
Write-Host " Cannot start without Python. Please install Python 3.8+ first." -ForegroundColor Red
return
}
# Check settings
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host " [ERROR] settings.yaml not found. You need to run setup first." -ForegroundColor Red
return
}
# Read current settings
$settingsJson = python -c "import yaml, json, sys, os; path = sys.argv[1]; d = yaml.safe_load(open(path, encoding='utf-8-sig')) or {} if os.path.exists(path) else {}; print(json.dumps(d))" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host " [ERROR] Failed to read settings.yaml" -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
# Enable debug logging - convert entire object to nested hashtables
function ConvertTo-HashTable($obj) {
$hash = @{}
if ($obj -eq $null) { return $hash }
$obj.PSObject.Properties | ForEach-Object {
if ($_.Value -is [System.Management.Automation.PSCustomObject]) {
$hash[$_.Name] = ConvertTo-HashTable $_.Value
} elseif ($_.Value -is [System.Array]) {
$hash[$_.Name] = @($_.Value)
} else {
$hash[$_.Name] = $_.Value
}
}
return $hash
}
$settingsHash = ConvertTo-HashTable $settings
if (-not $settingsHash.logging) {
$settingsHash.logging = @{}
}
$settingsHash.logging.debug_enabled = $true
$settingsHash.logging.level = "DEBUG"
# Convert back to JSON
$settingsJson = $settingsHash | ConvertTo-Json -Depth 10
# Save updated settings
$updateSettingsScript = @"
import yaml, sys, json
path = sys.argv[1]
data = json.loads(sys.stdin.read())
with open(path, 'w') as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
print('ok')
"@
$updateSettingsScript | Out-File -FilePath "$env:TEMP\update_settings_debug.py" -Encoding utf8 -Force
$settingsJson | python "$env:TEMP\update_settings_debug.py" $settingsFile 2>$null
Write-Host " [OK] Debug logging enabled in settings.yaml" -ForegroundColor Green
Write-Host " [OK] Log file: logs/debug.log" -ForegroundColor Green
Write-Host ""
Write-Host " Continuing with dashboard startup..." -ForegroundColor Yellow
Write-Host ""
# Now start the dashboard (reuses all the same logic but preserve debug)
Start-Dashboard -PreserveDebug
}
# ── New Dashboard (React + ChakraUI) ─────────────────────────────────────
function Start-NewDashboard {
param(
[switch]$PreserveDebug
)
Write-Host ""
Write-Host " Starting NEW dashboard (React + ChakraUI)..." -ForegroundColor Yellow
Write-Host ""
# Check Node.js
$nodeVersion = $null
try {
$nodeVersion = node --version 2>&1
Write-Host " Node.js: $nodeVersion" -ForegroundColor Green
} catch {
Write-Host " Node.js: NOT FOUND" -ForegroundColor Red
Write-Host ""
Write-Host " Node.js 18+ is required for the new frontend." -ForegroundColor Yellow
Write-Host " Download from https://nodejs.org/" -ForegroundColor Cyan
Write-Host ""
return
}
# ── Reuse tunnel/setup logic from Start-Dashboard ──────────────────────
# Check Python
if (-not (Test-Python)) {
return
}
# Check dependencies
Test-Dependencies | Out-Null
# Check settings
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host ""
Write-Host " [ERROR] settings.yaml not found. You need to run setup first." -ForegroundColor Red
Write-Host ""
return
}
# Read settings
$settingsJson = python -c "import yaml, json, sys, os; path = sys.argv[1]; d = yaml.safe_load(open(path, encoding='utf-8-sig')) or {} if os.path.exists(path) else {}; print(json.dumps(d))" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host " [ERROR] Failed to read settings.yaml" -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$LocalPort = [int]$settings.database.port
$Namespace = $settings.kubernetes.namespace
$DashboardPort = [int]$settings.dashboard.port
$DirectorPort = [int]$settings.director.port
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
Register-SensitiveValue -Key "Namespace" -Value $Namespace
Register-SensitiveValue -Key "DBPassword" -Value $settings.database.password
Register-SensitiveValue -Key "DBUser" -Value $settings.database.user
Register-SensitiveValue -Key "DashboardSecret" -Value $settings.dashboard.secret_key
Register-SensitiveValue -Key "DirectorToken" -Value $settings.director.token
Register-SensitiveValue -Key "AuthSecret" -Value $settings.auth.secret_key
# Find SSH key (same logic as Start-Dashboard)
function Test-SshKeyForNew($keyPath, $targetServer) {
if (-not (Test-Path $keyPath)) { return $false }
try {
$out = ssh -i $keyPath -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
return $out -eq "ok"
} catch { return $false }
}
$SSHKeySrc = $settings.server.ssh_key
$LocalKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
if ($SSHKeySrc -and $SSHKeySrc -ne 'null' -and -not [string]::IsNullOrEmpty($SSHKeySrc)) {
if (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost)) {
Register-SensitiveValue -Key "SSHKeyPath" -Value $SSHKeySrc
Write-Host " SSH Key: Using key from settings.yaml" -ForegroundColor Green
} else {
$SSHKeySrc = $null
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc) -or -not (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost))) {
$keyPaths = @(
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
$LocalKey,
"$env:USERPROFILE\.ssh\id_ed25519",
"$env:USERPROFILE\.ssh\id_rsa"
)
foreach ($kp in $keyPaths) {
if ($kp -ne $SSHKeySrc -and (Test-Path $kp)) {
if (Test-SshKeyForNew $kp ($SSHUser + '@' + $ServerHost)) {
$SSHKeySrc = $kp
Register-SensitiveValue -Key "SSHKeyPath" -Value $kp
Write-Host " SSH Key: Found working key at $kp" -ForegroundColor Green
break
}
}
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc)) {
Write-Host " [ERROR] No working SSH key found." -ForegroundColor Red
return
}
# Copy key to temp
$SSHKey = "$env:TEMP\dune-tunnel-key"
$ResolvedSrc = [System.IO.Path]::GetFullPath($SSHKeySrc)
$ResolvedDest = [System.IO.Path]::GetFullPath($SSHKey)
if ($ResolvedSrc -ne $ResolvedDest) {
Copy-Item $SSHKeySrc $SSHKey -Force
}
try {
$acl = Get-Acl $SSHKey -ErrorAction SilentlyContinue
if ($acl) {
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path $SSHKey -AclObject $acl -ErrorAction SilentlyContinue
}
} catch {}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Awakening Dashboard (React Edition)" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
# ── SSH Tunnel ────────────────────────────────────────────────────────
Write-Host "[1/5] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Start-Sleep 1
$sshArgs = @(
"-i", $SSHKey,
"-o", "StrictHostKeyChecking=accept-new",
"-o", "ServerAliveInterval=30",
"-o", "ServerAliveCountMax=3",
"-L", "${LocalPort}:localhost:${LocalPort}",
"-L", "${DirectorPort}:localhost:${DirectorPort}",
"-N", "${SSHUser}@${ServerHost}"
)
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
$connected = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
if ($sshTunnel.HasExited) {
Write-Host "[ERROR] SSH tunnel exited (code: $($sshTunnel.ExitCode))" -ForegroundColor Red
Write-Host " Check server IP and SSH key configuration." -ForegroundColor Yellow
return
}
try {
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("127.0.0.1", $LocalPort)
$tcp.Close()
$connected = $true
break
} catch {}
}
if (-not $connected) {
Write-Host "[ERROR] SSH tunnel did not connect within 30 seconds" -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green
# ── DB Port-Forward ───────────────────────────────────────────────────
Write-Host "[2/5] Starting DB port-forward on VM..." -ForegroundColor Yellow
if (-not $Namespace -or $Namespace -eq '') {
Write-Host "[ERROR] Kubernetes namespace is empty." -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
$DBService = "${Namespace}-db-dbdepl-svc"
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheck) {
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
if ($dbSvc) { $DBService = $dbSvc -replace 'service/', '' }
}
$RemotePort = 15432
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
Start-Sleep -Seconds 2
# BGD Director port-forward
$bgdSvc = "${Namespace}-bgd-svc"
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheckBgd) {
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
}
# Check BGD deployment
$bgdDeploy = "${Namespace}-bgd-deploy"
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
Start-Sleep -Seconds 15
}
$directorRemotePort = 11717
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
Start-Sleep -Seconds 3
# ── DB Check ──────────────────────────────────────────────────────────
Write-Host "[3/5] Checking database..." -ForegroundColor Yellow
$dbTest = $false
$dbScript = Join-Path $ProjectRoot "scripts\db_check.py"
for ($i = 0; $i -lt 15; $i++) {
try {
$result = python $dbScript $LocalPort 2>$null
if ($result -match 'ok') { $dbTest = $true; break }
} catch {}
Start-Sleep -Seconds 1
}
if (-not $dbTest) {
Write-Host "[ERROR] Database connection failed." -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] Database connected" -ForegroundColor Green
# ── Install Dependencies ──────────────────────────────────────────────
Write-Host "[4/5] Installing dependencies..." -ForegroundColor Yellow
# Backend Python deps (project root requirements.txt)
if (Test-Path (Join-Path $ProjectRoot "requirements.txt")) {
Write-Host " Checking backend Python dependencies..." -ForegroundColor DarkGray
$pipArgs = @("pip", "install", "-r", (Join-Path $ProjectRoot "requirements.txt"), "--quiet")
& python @pipArgs 2>$null
$pipArgs2 = @("pip", "install", "psycopg[binary]", "--quiet")
& python @pipArgs2 2>$null
Write-Host " Backend dependencies OK" -ForegroundColor Green
}
# Frontend npm deps
$frontendDir = Join-Path $ProjectRoot "frontend"
if (Test-Path (Join-Path $frontendDir "package.json")) {
$nodeModulesDir = Join-Path $frontendDir "node_modules"
if (-not (Test-Path $nodeModulesDir)) {
Write-Host " Installing frontend npm dependencies..." -ForegroundColor DarkGray
$prevLoc = Get-Location
Set-Location -LiteralPath $frontendDir
npm install 2>&1 | Out-Null
Set-Location -LiteralPath $prevLoc
Write-Host " Frontend dependencies installed" -ForegroundColor Green
} else {
Write-Host " Frontend dependencies OK" -ForegroundColor Green
}
}
# ── Start Backend + Frontend ──────────────────────────────────────────
Write-Host "[5/5] Starting dashboard..." -ForegroundColor Yellow
Write-Host ""
# Start the new Flask API backend
Write-Host " Starting backend API (port $DashboardPort)..." -ForegroundColor Cyan
$backendDir = Join-Path $ProjectRoot "backend"
$backendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$backendDir`" && python run.py" -PassThru
# Wait for backend to be ready
Write-Host " Waiting for backend to start..." -ForegroundColor DarkGray
$backendAlive = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
try {
$wc = New-Object System.Net.WebClient
$result = $wc.DownloadString("http://127.0.0.1:${DashboardPort}/api/stats")
if ($result) { $backendAlive = $true; break }
} catch {}
}
if (-not $backendAlive) {
Write-Host "[ERROR] Backend failed to start within 30 seconds." -ForegroundColor Red
Write-Host " Check the backend window for errors." -ForegroundColor Yellow
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host " [OK] Backend API running on port $DashboardPort" -ForegroundColor Green
# Start frontend in a visible window
Write-Host " Starting frontend dev server (port 5173)..." -ForegroundColor Cyan
$viteDir = Join-Path $ProjectRoot "frontend"
$frontendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$viteDir`" && npm run dev -- --host 0.0.0.0" -PassThru
Start-Sleep -Seconds 6
# Check if frontend is running by probing the port
$frontendAlive = $false
try {
$wc = New-Object System.Net.WebClient
$wc.DownloadString("http://127.0.0.1:5173/") | Out-Null
$frontendAlive = $true
} catch {}
if (-not $frontendAlive) {
Write-Host "[WARN] Frontend may not have started yet. Check the frontend window." -ForegroundColor Yellow
} else {
Write-Host " [OK] Frontend running on port 5173" -ForegroundColor Green
}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " New Dashboard Started!" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " Frontend: http://localhost:5173" -ForegroundColor Cyan
Write-Host " Backend: http://localhost:${DashboardPort}" -ForegroundColor DarkGray
Write-Host ""
Write-Host " Open http://localhost:5173 in your browser" -ForegroundColor Yellow
Write-Host ""
Write-Host " Close the backend and frontend windows to stop, or" -ForegroundColor DarkGray
Write-Host " press Enter here to kill the SSH tunnel and all processes." -ForegroundColor DarkGray
Write-Host ""
Read-Host " Press Enter to stop"
Write-Host ""
Write-Host " Stopping services..." -ForegroundColor Cyan
Stop-Process -Id $frontendProcess.Id -Force -ErrorAction SilentlyContinue
Stop-Process -Id $backendProcess.Id -Force -ErrorAction SilentlyContinue
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k ' + $LocalPort + '/tcp ' + $DirectorPort + '/tcp 2>/dev/null"'
cmd /c $pkillCmd 2>$null
Write-Host " All services stopped." -ForegroundColor Green
Write-Host ""
}
function Repair-GameDatabase {
Write-Host ""
Write-Host " Game Database Repair" -ForegroundColor Cyan
Write-Host " =====================" -ForegroundColor Cyan
Write-Host ""
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host "[ERROR] settings.yaml not found. Run setup first (option 2)." -ForegroundColor Red
return
}
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host "[ERROR] Could not read settings.yaml." -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$Namespace = $settings.kubernetes.namespace
$SSHKey = $null
if ($settings.server.ssh_key -and $settings.server.ssh_key -ne 'null') {
$SSHKey = $settings.server.ssh_key
}
if (-not $SSHKey) {
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
}
if (-not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP') {
Write-Host "[ERROR] Server IP not configured in settings.yaml." -ForegroundColor Red
return
}
if (-not $Namespace) {
Write-Host "[ERROR] Kubernetes namespace not configured." -ForegroundColor Red
return
}
if (-not (Test-Path $SSHKey)) {
Write-Host "[ERROR] SSH key not found at: $SSHKey" -ForegroundColor Red
return
}
Write-Host " Server: $ServerHost" -ForegroundColor White
Write-Host " Namespace: $Namespace" -ForegroundColor White
Write-Host ""
$confirm = Read-Host " This will transfer dashboard schema ownership to the dune user. Continue? (y/N)"
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
Write-Host " Cancelled." -ForegroundColor Yellow
return
}
Write-Host ""
# 1. Find the database pod
Write-Host "[1/4] Finding database pod..." -ForegroundColor Yellow
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
if (-not $dbPod) {
Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red
return
}
Write-Host " [OK] Database pod: $dbPod" -ForegroundColor Green
# 2. Run the ownership fix SQL
Write-Host "[2/4] Running ownership fix..." -ForegroundColor Yellow
# Build a temp .ps1 script where each line uses --% with values directly embedded.
# After --%, PowerShell passes everything literally to ssh.exe — no parsing issues.
$tmpFile = Join-Path $env:TEMP "dune_repair_$([System.IO.Path]::GetRandomFileName()).ps1"
$sshBase = "ssh --% -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -i `"$SSHKey`" `"$SSHUser@$ServerHost`""
$scriptLines = @(
"$sshBase `"printf 'ALTER SCHEMA dashboard OWNER TO dune;\n' > /tmp/repair.sql`""
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER TABLE dashboard.\x27 || quote_ident(r.tablename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER SEQUENCE dashboard.\x27 || quote_ident(r.sequencename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON TABLES TO dune;\n' >> /tmp/repair.sql`""
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON SEQUENCES TO dune;\n' >> /tmp/repair.sql`""
"$sshBase `"cat /tmp/repair.sql | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune`""
"$sshBase `"printf 'CREATE SCHEMA IF NOT EXISTS dashboard;\nGRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;\n' | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d template1`""
)
$scriptLines | Out-File -FilePath $tmpFile -Encoding ASCII
$sqlResult = powershell -NoProfile -File $tmpFile 2>&1
Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue
Write-Host " $sqlResult" -ForegroundColor DarkGray
Write-Host " [OK] Ownership fix applied" -ForegroundColor Green
# 3. Delete failed util pods
Write-Host "[3/4] Cleaning up failed utility pods..." -ForegroundColor Yellow
$deleted = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace | grep 'db.*util' | grep -v Running | awk '{print \$1}' | xargs -r sudo kubectl delete pod -n $Namespace --wait=false" 2>$null
if ($deleted) {
Write-Host " $deleted" -ForegroundColor DarkGray
Write-Host " [OK] Failed util pods deleted" -ForegroundColor Green
} else {
Write-Host " [OK] No failed util pods found" -ForegroundColor Green
}
# 4. Instructions
Write-Host "[4/4] Done!" -ForegroundColor Yellow
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Repair Complete!" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " If game servers still show errors, restart the battlegroup:" -ForegroundColor White
Write-Host " 1. In the battlegroup management UI, select option 5" -ForegroundColor White
Write-Host " (Restart battlegroup)" -ForegroundColor DarkGray
Write-Host " 2. Wait for all pods to come back healthy" -ForegroundColor White
Write-Host ""
Write-Host " The dashboard will auto-fix ownership on every startup," -ForegroundColor Green
Write-Host " so this should not happen again." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return to the menu..." -ForegroundColor DarkGray
Read-Host
}
function Cleanup-OldDashboardSchema {
Write-Host ""
Write-Host " Clean Up Old Dashboard Schema" -ForegroundColor Cyan
Write-Host " ===============================" -ForegroundColor Cyan
Write-Host ""
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if ( -not (Test-Path $settingsFile) ) {
Write-Host "[ERROR] settings.yaml not found." -ForegroundColor Red
return
}
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
if ( -not $settingsJson ) { Write-Host "[ERROR] Could not read settings." -ForegroundColor Red; return }
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$Namespace = $settings.kubernetes.namespace
$SSHKey = $settings.server.ssh_key
if ( -not $SSHKey -or $SSHKey -eq 'null' ) {
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
}
if ( -not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP' ) { Write-Host "[ERROR] Server IP not configured." -ForegroundColor Red; return }
if ( -not $Namespace ) { Write-Host "[ERROR] Namespace not configured." -ForegroundColor Red; return }
if ( -not (Test-Path $SSHKey) ) { Write-Host "[ERROR] SSH key not found." -ForegroundColor Red; return }
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
if ( -not $dbPod ) { Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red; return }
$hasOldSchema = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -t -c ""SELECT count(*) FROM information_schema.schemata WHERE schema_name = 'dashboard'"" 2>&1" 2>$null
$hasOldSchema = $hasOldSchema.Trim()
if ( $hasOldSchema -eq '0' ) {
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
if ( -not $hasOldSchema ) {
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
Write-Host " [WARN] Old dashboard schema found in the game database." -ForegroundColor Yellow
Write-Host ""
Write-Host " This drops: dashboard.audit_log, dashboard.bans, dashboard.player_ips," -ForegroundColor White
Write-Host " dashboard.player_actions, dashboard.chat_history, dashboard.settings" -ForegroundColor White
Write-Host ""
Write-Host " Make sure the dashboard has migrated this data to the new database first." -ForegroundColor Yellow
Write-Host " (The dashboard does this automatically on next startup.)" -ForegroundColor DarkGray
Write-Host ""
$confirm = Read-Host " Type 'yes' to drop the old dashboard schema"
if ($confirm -ne 'yes') {
Write-Host " Cancelled." -ForegroundColor Yellow
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
$confirm2 = Read-Host " REALLY drop? This cannot be undone. Type 'yes' again"
if ($confirm2 -ne 'yes') {
Write-Host " Cancelled." -ForegroundColor Yellow
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
return
}
Write-Host ""
Write-Host " Dropping old dashboard schema..." -ForegroundColor Yellow
$result = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -c ""DROP SCHEMA IF EXISTS dashboard CASCADE"" 2>&1"
Write-Host " $result" -ForegroundColor DarkGray
Write-Host " [OK] Old dashboard schema dropped." -ForegroundColor Green
Write-Host ""
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
Read-Host
}
# ── Main Loop ───────────────────────────────────────────────────────────
Show-Banner
while ($true) {
Show-Menu
$choice = Read-Host " Enter your choice"
switch ($choice) {
"1" { Start-Dashboard; break }
"2" { Run-Setup; break }
"3" { Run-Diagnostics; break }
"4" { Install-CaCert; break }
"5" { Clean-CaCerts; break }
"6" { Start-DashboardDebug; break }
"7" { Start-NewDashboard; break }
"8" { Reset-ToFactoryDefaults; break }
"9" { Repair-GameDatabase; break }
"10" { Cleanup-OldDashboardSchema; break }
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-10, or Q." -ForegroundColor Yellow; Write-Host "" }
}
Write-Host ""
}