#Requires -Version 5.1
<#
.SYNOPSIS
  Deploy God Mode / licensing patches, then generate a new platform access code (non-interactive).

.EXAMPLE
  cd deploy\hetzner
  ssh-add $env:USERPROFILE\.ssh\id_ed25519_cnperp
  .\Deploy-And-Reset-GodMode.ps1
#>
$ErrorActionPreference = "Stop"
$Here = $PSScriptRoot
. (Join-Path $Here "Quick-Deploy-GodModePatch.ps1")

Write-Host "`n--- Resetting God Mode platform secret ---" -ForegroundColor Cyan
$sshArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=30")
$scpArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes")
$resetSh = Join-Path $Here "reset-platform-secret.sh"
scp @scpArgs $resetSh "root@${ServerIp}:/tmp/reset-platform-secret.sh"
$out = ssh @sshArgs "root@$ServerIp" "sed -i 's/\r$//' /tmp/reset-platform-secret.sh; chmod +x /tmp/reset-platform-secret.sh; bash /tmp/reset-platform-secret.sh" 2>&1
$out | ForEach-Object { Write-Host $_ }

$secretLine = ($out | Where-Object { $_ -match '^\s*Secret:\s+' }) -replace '^\s*Secret:\s+', ''
if ($secretLine) {
    $secret = $secretLine.Trim()
    $localPs1 = Join-Path $Here "production.local.ps1"
    if (Test-Path $localPs1) {
        $content = Get-Content $localPs1 -Raw
        if ($content -match '(?m)^\$LicenseAdminSecret\s*=') {
            $content = $content -replace '(?m)^\$LicenseAdminSecret\s*=.*', "`$LicenseAdminSecret = `"$secret`""
        } else {
            $content = $content.TrimEnd() + "`n`$LicenseAdminSecret = `"$secret`"`n"
        }
        Set-Content -Path $localPs1 -Value $content -NoNewline
        Write-Host "`nSaved LicenseAdminSecret to production.local.ps1 (future deploys will keep this code)." -ForegroundColor Green
    }
    Write-Host "`n*** SAVE THIS GOD MODE ACCESS CODE ***" -ForegroundColor Yellow
    Write-Host $secret -ForegroundColor White
    Write-Host "Login: https://$Domain/platform-admin" -ForegroundColor Green
} else {
    Write-Host "`nReset ran - check output above for Secret: line." -ForegroundColor Yellow
}
