#!/bin/bash
# panel-admin-hosts — make the admin panel reachable as https://<any site domain>:8443/ with that site's real certificate.
# Regenerates /etc/panel/admin-hosts.conf (one :8443 vhost per site that has SSL). Called by panel-site-add.
# Access rules are identical for every hostname (IP allowlist + login + 2FA), see /etc/panel/admin-common.conf.
. /opt/panel/bin/panel-lib.sh
shopt -s nullglob
out=/etc/panel/admin-hosts.conf
[ -f /etc/panel/admin-common.conf ] || exit 0
{
  echo "# managed by panel-admin-hosts — do not edit"
  for conf in "$PANEL_VHOSTS"/*.conf; do
    d=$(basename "$conf" .conf)
    c="$PANEL_SSL/$d/fullchain.pem"; k="$PANEL_SSL/$d/privkey.pem"
    [ -s "$c" ] && [ -s "$k" ] || continue
    alias=""
    openssl x509 -in "$c" -noout -ext subjectAltName 2>/dev/null | grep -q "DNS:www.$d" && alias="    ServerAlias www.$d"
    printf '<VirtualHost *:8443>\n    ServerName %s\n%s\n    SSLEngine on\n    SSLCertificateFile %s\n    SSLCertificateKeyFile %s\n    Include /etc/panel/admin-common.conf\n</VirtualHost>\n' \
      "$d" "$alias" "$c" "$k"
  done
} > "$out.new"
mv "$out.new" "$out"
