#!/bin/bash
# panel-ssl-status — JSON list of all sites with docroot, SSL issuer/expiry and whether DNS points here.
. /opt/panel/bin/panel-lib.sh
shopt -s nullglob
ip=$(server_ip)
# the result is also saved for the panel pages (refreshed every 10 minutes by panel-usage.service)
CACHE=/var/lib/panel/ssl-status.json; tmp=$(mktemp /var/lib/panel/.ssl-status.XXXXXX)
exec 3>&1 > "$tmp"
echo "{\"server_ip\":\"$ip\",\"generated\":$(date +%s),\"sites\":["
first=1
for conf in "$PANEL_VHOSTS"/*.conf; do
  d=$(basename "$conf" .conf)
  cert="$PANEL_SSL/$d/fullchain.pem"
  days=$(cert_days "$cert")
  issuer=""; [ -s "$cert" ] && issuer=$(openssl x509 -in "$cert" -noout -issuer 2>/dev/null | sed -n 's/.*O *= *\([^,]*\).*/\1/p' | tr -d '"')
  a=$(dns_a "$d")
  here=false; [[ " $a " == *" $ip "* ]] && here=true
  [ $first = 1 ] || echo ","; first=0
  printf '{"domain":"%s","docroot":"%s","user":"%s","ssl_days":%s,"ssl_issuer":"%s","dns":"%s","dns_here":%s}' \
    "$d" "$(site_docroot "$d")" "$(site_user "$d")" "$days" "${issuer//\"/}" "$a" "$here"
done
echo "]}"
exec 1>&3 3>&-
chmod 644 "$tmp"; mv -f "$tmp" "$CACHE"; cat "$CACHE"
