# Push ERP-only Caddy config to Hetzner and reload (run from repo root).
#Requires -Version 5.1
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "production.local.ps1")

$sshArgs = @("-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=120")
if ($SshKeyPath -and (Test-Path $SshKeyPath)) {
    $sshArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes") + $sshArgs
}

$fix = Join-Path $PSScriptRoot "fix-caddy-tls.sh"
scp @sshArgs $fix "root@${ServerIp}:/tmp/fix-caddy-tls.sh"
$marketing = if ($MarketingDomain) { $MarketingDomain } else { "cnpsolutions.co.bw" }
ssh @sshArgs "root@$ServerIp" "sed -i 's/\r$//' /tmp/fix-caddy-tls.sh; chmod +x /tmp/fix-caddy-tls.sh; CNPERP_DOMAIN='$Domain' CNPERP_MARKETING_DOMAIN='$marketing' bash /tmp/fix-caddy-tls.sh"

Write-Host ""
Write-Host "Caddy updated on $ServerIp" -ForegroundColor Green
Write-Host "DNS must be: erp -> $ServerIp  (see deploy\hetzner\POINT_DNS_ERP.md)" -ForegroundColor Yellow
Write-Host "Test after DNS: https://$Domain/" -ForegroundColor Cyan
Write-Host "Until DNS:      http://$ServerIp/" -ForegroundColor Gray
