#!/usr/bin/env bash
set -euo pipefail
DOMAIN="${CERTBOT_DOMAIN:-}"
LINEAGE="${RENEWED_LINEAGE:-${CERTBOT_RENEWED_LINEAGE:-}}"
[[ "$DOMAIN" =~ ^[A-Za-z0-9][A-Za-z0-9.-]{0,251}$ ]] || exit 0
[[ -n "$LINEAGE" && -f "$LINEAGE/fullchain.pem" && -f "$LINEAGE/privkey.pem" ]] || exit 0
# The domain is validated above and used only as a path component.
install -d -m 0755 "/etc/scpanel/ssl/$DOMAIN"
install -m 0644 "$LINEAGE/fullchain.pem" "/etc/scpanel/ssl/$DOMAIN/fullchain.pem"
install -m 0600 "$LINEAGE/privkey.pem" "/etc/scpanel/ssl/$DOMAIN/privkey.pem"
# Safely reload only installed web servers. Their own config tests are performed
# by SCpanel when the certificate is attached/HTTPS is changed.
if command -v nginx >/dev/null 2>&1 && systemctl is-active --quiet nginx; then systemctl reload nginx || true; fi
if command -v apache2ctl >/dev/null 2>&1 && systemctl is-active --quiet apache2; then systemctl reload apache2 || true; fi
# Refresh SCpanel's certificate inventory metadata when the panel runtime exists.
if [[ -x /opt/scpanel/venv/bin/python ]]; then
  /opt/scpanel/venv/bin/python - "$DOMAIN" <<'PY' || true
import sys, sqlite3, subprocess
from pathlib import Path
from datetime import datetime, timezone
D=Path('/var/lib/scpanel/scpanel.db'); domain=sys.argv[1]
if not D.exists(): raise SystemExit
crt=Path('/etc/scpanel/ssl')/domain/'fullchain.pem'
if not crt.exists(): raise SystemExit
r=subprocess.run(['openssl','x509','-in',str(crt),'-noout','-startdate','-enddate'],capture_output=True,text=True)
vals={}
for line in r.stdout.splitlines():
    if '=' in line:
        k,v=line.split('=',1); vals[k]=v

def iso(v):
    try:return datetime.strptime(v,'%b %d %H:%M:%S %Y %Z').replace(tzinfo=timezone.utc).isoformat()
    except:return ''
c=sqlite3.connect(D);c.execute("UPDATE ssl_certificates SET status='valid',issued_at=?,expires_at=?,last_renewed_at=CURRENT_TIMESTAMP,updated_at=CURRENT_TIMESTAMP WHERE domain=?",(iso(vals.get('notBefore','')),iso(vals.get('notAfter','')),domain));c.commit();c.close()
PY
fi
