# Finish install on server after numpy/pip failure (no full re-extract).
$ErrorActionPreference = "Stop"
& (Join-Path $PSScriptRoot "_write-requirements-utf8.ps1")
. (Join-Path $PSScriptRoot "production.local.ps1")
$key = (& "$PSScriptRoot\_prepare-deploy-key.ps1" | Select-Object -Last 1).Trim()
$ssh = @("-i", $key, "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=120")
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

scp @ssh (Join-Path $repo "requirements.txt") "root@${ServerIp}:/tmp/cnperp-requirements.txt"
scp @ssh (Join-Path $PSScriptRoot "bootstrap-production.sh") "root@${ServerIp}:/tmp/cnperp-bootstrap.sh"
scp @ssh (Join-Path $PSScriptRoot "resume-bootstrap.sh") "root@${ServerIp}:/tmp/cnperp-resume.sh"
foreach ($f in @("run-migrations.sh", "init-db-schema.sh")) {
    $p = Join-Path $PSScriptRoot $f
    if (Test-Path $p) { scp @ssh $p "root@${ServerIp}:/tmp/cnperp-$f" }
}

$cmd = @(
    "export CNPERP_DOMAIN='$Domain'"
    "export CNPERP_MARKETING_DOMAIN='$MarketingDomain'"
    "export CNPERP_DB_PASSWORD='$DbPassword'"
    "cp /tmp/cnperp-run-migrations.sh /opt/cnperp/deploy/hetzner/run-migrations.sh 2>/dev/null || true"
    "cp /tmp/cnperp-init-db-schema.sh /opt/cnperp/deploy/hetzner/init-db-schema.sh 2>/dev/null || true"
    "chmod +x /opt/cnperp/deploy/hetzner/init-db-schema.sh 2>/dev/null || true"
    "sudo -u cnperp /opt/cnperp/deploy/hetzner/init-db-schema.sh /opt/cnperp"
    "sed -i 's/\r$//' /tmp/cnperp-bootstrap.sh /tmp/cnperp-resume.sh"
    "bash /tmp/cnperp-resume.sh"
) -join "; "

Write-Host "Resuming pip + services on $ServerIp (numpy 1.26.4 fix)..." -ForegroundColor Cyan
ssh @ssh "root@$ServerIp" $cmd
$code = $LASTEXITCODE
Remove-Item -Force $key, "$key.pub" -ErrorAction SilentlyContinue
if ($code -eq 0) {
    Write-Host "`nResume OK. Open https://$Domain/setup" -ForegroundColor Green
} else {
    Write-Host "`nResume failed (exit $code). Check: ssh root@$ServerIp tail -50 /tmp/cnperp-bootstrap.log" -ForegroundColor Red
}
Read-Host "Press Enter to close"
exit $code
