# Automated deploy (visible terminal). Uses a temporary key in %TEMP% for this session only.
$ErrorActionPreference = "Stop"
$RepoRoot = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$logFile = Join-Path $PSScriptRoot "_last-deploy.log"
$deployKey = (& "$PSScriptRoot\_prepare-deploy-key.ps1" | Select-Object -Last 1).Trim()
Write-Host "CNPERP Hetzner deploy -> 178.105.218.193 (erp.cnpsolutions.co.bw)" -ForegroundColor Cyan
Write-Host "Log file: $logFile`n" -ForegroundColor Gray
try {
    Set-Location $RepoRoot
    & "$PSScriptRoot\Start-HetznerProduction.ps1" -UseLocalCode -Resume -SshKeyPathOverride $deployKey 2>&1 |
        Tee-Object -FilePath $logFile
    $code = $LASTEXITCODE
} finally {
    Remove-Item -Force $deployKey, "$deployKey.pub" -ErrorAction SilentlyContinue
}
Write-Host ""
if ($code -eq 0) {
    Write-Host "Deploy finished OK. Open https://erp.cnpsolutions.co.bw/setup" -ForegroundColor Green
} else {
    Write-Host "Deploy failed (exit $code). See $logFile" -ForegroundColor Red
}
if ([Environment]::UserInteractive) {
    Read-Host "Press Enter to close this window"
}
exit $code
