#!/usr/bin/env bash
# Fix HTTPS for erp + www + apex (all must be in DNS -> this server IP).
set -euo pipefail
[[ "$(id -u)" -eq 0 ]] || { echo "Run as root"; exit 1; }

CNPERP_DOMAIN="${CNPERP_DOMAIN:-erp.cnpsolutions.co.bw}"
MARKETING_DOMAIN="${CNPERP_MARKETING_DOMAIN:-cnpsolutions.co.bw}"
EMAIL="${CADDY_ACME_EMAIL:-admin@cnpsolutions.co.bw}"
SERVER_IP="${SERVER_IP:-$(curl -fsS --max-time 5 ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')}"

echo "Server IP: ${SERVER_IP}"
for h in "${CNPERP_DOMAIN}" "www.${MARKETING_DOMAIN}" "${MARKETING_DOMAIN}"; do
  ip=$(dig +short "$h" A 2>/dev/null | tail -1)
  ok=""
  [[ "$ip" == "$SERVER_IP" ]] && ok=" OK" || ok=" MISMATCH (points to ${ip:-none})"
  echo "  $h -> ${ip:-<none>}${ok}"
done
echo ""

cat > /etc/caddy/Caddyfile <<CADDY
{
    email ${EMAIL}
}

${CNPERP_DOMAIN}, www.${MARKETING_DOMAIN}, ${MARKETING_DOMAIN} {
    reverse_proxy 127.0.0.1:8000
    encode gzip
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains"
        X-Content-Type-Options nosniff
        X-Frame-Options SAMEORIGIN
        Referrer-Policy strict-origin-when-cross-origin
    }
}

http://${SERVER_IP} {
    reverse_proxy 127.0.0.1:8000
    encode gzip
}
CADDY

echo "Caddyfile written. Validating..."
caddy validate --config /etc/caddy/Caddyfile

echo "Resetting ACME cache and restarting Caddy..."
systemctl stop caddy
rm -rf /var/lib/caddy/.local/share/caddy/certificates
rm -rf /var/lib/caddy/.local/share/caddy/acme
systemctl start caddy

for i in 1 2 3 4 5 6 7 8 9 10; do
  sleep 3
  if curl -fsS --max-time 3 "https://${CNPERP_DOMAIN}/" -o /dev/null 2>/dev/null; then
    echo ""
    echo "HTTPS OK: https://${CNPERP_DOMAIN}/"
    exit 0
  fi
  echo "  waiting for certificate... (${i}/10)"
done

echo ""
echo "Caddy is running but HTTPS may still be issuing. Check:"
echo "  journalctl -u caddy -n 40 --no-pager"
echo "  curl -vI https://${CNPERP_DOMAIN}/"
exit 0
