#!/bin/bash
# panel-ssl-issue <domain>  — get a free Let's Encrypt certificate for a site (and www. if it points here too).
# Requires the domain's DNS A record to point to this server. Renewal is automatic (certbot-renew.timer).
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
LOGNAME_PANEL=ssl
if [ "${1:-}" = on ]; then   # the same on a connected server
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  exec timeout 150 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-ssl-issue $(printf '%q ' "$@")"
fi
d="${1:-}"; retry="${2:-}"
valid_domain "$d" || die "invalid domain: $d"
[ -f "$(site_conf "$d")" ] || die "no site configured for $d"
ip=$(server_ip)
# --retry[=N]: when DNS has not switched yet, try again every 5 minutes (N more times, default 24 = two hours)
if [[ "$retry" =~ ^--retry(=([0-9]+))?$ ]] && ! dns_points_here "$d"; then
  left="${BASH_REMATCH[2]:-24}"
  if [ "$left" -gt 0 ]; then
    systemd-run --quiet --on-active=300 --unit="panel-ssl-retry-${d//./-}-$left" /opt/panel/bin/panel-ssl-issue "$d" "--retry=$((left - 1))" >/dev/null 2>&1 || true
    log "$d: DNS not here yet — trying again in 5 minutes ($left tries left)"
    echo "DNS for $d does not point to this server yet ($(dns_a "$d")). The certificate is requested automatically as soon as it does (checked every 5 minutes)."
    exit 0
  fi
fi
dns_points_here "$d" || { log "$d: skipped — DNS points to '$(dns_a "$d")', not $ip"; die "DNS for $d points to '$(dns_a "$d")', not to this server ($ip). Change the A record first."; }
names=(-d "$d"); shown="$d"
dns_points_here "www.$d" && { names+=(-d "www.$d"); shown="$d, www.$d"; }
mkdir -p /var/www/acme/.well-known/acme-challenge
if certbot certonly --webroot -w /var/www/acme --cert-name "$d" "${names[@]}" \
     --non-interactive --agree-tos --register-unsafely-without-email \
     --keep-until-expiring --expand --deploy-hook /opt/panel/bin/panel-ssl-deploy >> "$PANEL_LOG/certbot.log" 2>&1; then
  # also deploy when certbot kept an existing, still-valid certificate
  RENEWED_LINEAGE="/etc/letsencrypt/live/$d" /opt/panel/bin/panel-ssl-deploy
  log "$d: certificate ok ($shown)"
  echo "Let's Encrypt certificate ok for $shown"
else
  log "$d: Let's Encrypt FAILED — see $PANEL_LOG/certbot.log"
  tail -15 "$PANEL_LOG/certbot.log" >&2
  die "Let's Encrypt failed for $d"
fi
