#!/bin/bash
# Wombat-Email: the daily report (installed by installer/95-report.sh as /usr/local/sbin/wombat-email-report,
# run by wombat-email-report.timer at 06:00 local time). Mailed to the owner (ADMIN_EMAIL), or to
# REPORT_TO when the owner set one.
# The layout: what needs attention first, then == sections == of [ok] / [WARN] / [CRIT] lines, and
# the overall status last (in the subject too). The lists per address are in the weekly report.
#   wombat-email-report --print     to the screen instead of mailing it
#   wombat-email-report --message   the whole message as it would be mailed (headers too), not sent
set -uo pipefail
. /etc/wombat-email/settings
PRINT=0; [ "${1:-}" = --print ] && PRINT=1
MAILING=0; [ -z "${1:-}" ] && MAILING=1   # only the morning's run moves "yesterday" on: --print and --message leave it
host=$(hostname -f)
attention=()
need() { attention+=("$*"); }

# ---- the backup: ok, and from the last 26 hours
read -r b_state b_age b_msg < <(python3 -I -c '
import json, time
try:
    s = json.load(open("/var/lib/wombat-email/backup-status.json"))
    print(s["state"], int((time.time() - s["finished"]) / 3600), s["message"])
except Exception:
    print("none", -1, "no backup has run yet")' 2>/dev/null)
if [ "$b_state" != ok ]; then need "Backup: $b_msg"
elif [ "$b_age" -gt 26 ]; then need "Backup: the last one finished $b_age hours ago"
fi

# ---- certificates: three weeks' warning (they renew at 30 days left, so this means renewal is failing)
for c in /etc/letsencrypt/live/*/fullchain.pem; do
    [ -f "$c" ] || continue
    end=$(openssl x509 -in "$c" -noout -enddate | cut -d= -f2)
    days=$(( ($(date -d "$end" +%s) - $(date +%s)) / 86400 ))
    [ "$days" -ge 21 ] || need "Certificate $(basename "$(dirname "$c")") expires in $days days (renewal isn't working: certbot renew --dry-run)"
done

# ---- the nightly mail test
if [ -f /var/lib/wombat-email/mailtest-status.json ]; then
    mt=$(python3 -I -c 'import json; s=json.load(open("/var/lib/wombat-email/mailtest-status.json")); print("; ".join(s["failed"]))')
    [ -z "$mt" ] || need "Nightly mail test failed: $mt"
fi

# ---- Rspamd: an update from rspamd.com waiting (it installs with Ubuntu's, from the panel's Updates)
inst=$(dpkg-query -W -f='${Version}' rspamd 2>/dev/null || true)
cand=$(apt-cache policy rspamd 2>/dev/null | awk '/Candidate:/ {print $2}')
[ -z "$inst" ] || [ -z "$cand" ] || [ "$cand" = "$inst" ] || [ "$cand" = "(none)" ] \
    || need "Rspamd update waiting: ${cand%%-*} (installed ${inst%%-*}): it installs with Ubuntu's updates (Server › Updates)"

# ---- webmail: its morning update, and a new series (taken by hand, it can change more)
w=$(python3 -I -c 'import json; s=json.load(open("/var/lib/wombat-email/webmail.json")); print(s["error"] or (("Roundcube " + s["newer_series"] + " is out: a new series, not installed by itself") if s["newer_series"] else ""))' 2>/dev/null)
[ -z "$w" ] || need "Webmail: $w"

# ---- Wombat-Email itself: a newer version on wombat-email.com (installed from the panel: Status, Update)
we_mine=$(cat /opt/wombat-email/VERSION 2>/dev/null)
# over IPv4 only: a server with IPv6 too would otherwise count twice on the site's map on a day it asked both ways
we_latest=$(curl -4 -fsS --max-time 10 -A "Wombat-Email/$we_mine" https://wombat-email.com/wombat-email/VERSION 2>/dev/null | head -c 20 | tr -dc '0-9.')
we_cmp=$we_mine; [[ "$we_latest" == 0.* && "$we_mine" =~ ^1\.[0-9]+\.[0-9]+$ ]] && we_cmp=0.${we_mine#1.}   # renumbered 1.x -> 0.x
if [[ "$we_latest" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] && [ "$we_latest" != "$we_cmp" ] \
   && [ "$(printf '%s\n%s\n' "$we_cmp" "$we_latest" | sort -V | tail -1)" = "$we_latest" ]; then
    need "Wombat-Email v$we_latest is available"
fi

# ---- mailboxes' public keys (private or published): checked again every morning, so a key that ended leaves
# the key directory today; one that ends within 30 days is named, so its owner can renew it in time
if [ -x /usr/local/sbin/wombat-email-pgp-keys ]; then
    pk=$(/usr/local/sbin/wombat-email-pgp-keys 2>&1) || true
    grep -qx transport <<<"$pk" && systemctl reload postfix
    while IFS= read -r k; do [ -z "$k" ] || need "$k"; done < <(python3 -I -c '
import json, time
try:
    keys = json.load(open("/var/lib/wombat-email/pgp-keys.json"))["keys"]
except Exception:
    keys = {}
for addr, k in sorted(keys.items()):
    end = k.get("ends")
    kind = "Private mailbox " if k.get("private") else "Published key of "
    if end is not None and end <= time.time():
        print(kind + addr + ": its key has ended " + time.strftime("%b %-d", time.localtime(end)) + (
              ", so its new mail waits in the queue (5 days at most) until its owner sends a renewed key" if k.get("private")
              else ", so it is no longer published until its owner sends a renewed key"))
    elif end is not None and end - time.time() < 30 * 86400:
        print(kind + addr + ": its key ends " + time.strftime("%b %-d", time.localtime(end)) +
              ": its owner renews it (in their mail app, change the key end date and send the key again)")
    elif k.get("problem") and k.get("private"):
        print(kind + addr + ": its key " + k["problem"] + ", so its new mail waits in the queue")' 2>/dev/null)
fi

# ---- pictures in mail (91-images): those of messages that are gone go too
[ -x /usr/local/libexec/wombat-email-images ] && /usr/local/libexec/wombat-email-images --clean >/dev/null 2>&1 || true

# ---- services, disk, queue, restart
for s in postfix dovecot rspamd redis-server clamav-daemon unbound postgresql fail2ban; do
    systemctl is-active --quiet "$s" || need "Service $s isn't running"
done
disk=$(df --output=pcent / | tail -1 | tr -dc 0-9)
[ "$disk" -lt 85 ] || need "Disk ${disk}% full"
queue=$(postqueue -j 2>/dev/null | grep -c . || true)
[ "$queue" -lt 50 ] || need "$queue messages waiting in the mail queue (postqueue -p)"
[ ! -f /var/run/reboot-required ] || need "An update needs a restart: in the panel, Settings, Restart the server"

# ---- the big providers: mail they refused or held back in the last 24 hours, from their block lists or
# checks (wombat-email-delivery). Needs attention only while nothing has reached that provider since.
delivery=$(/usr/local/libexec/wombat-email-delivery 24 --json 2>/dev/null || echo '{}')
/usr/local/libexec/wombat-email-delivery 168 --save 2>/dev/null || true   # the panel's copy, the last 7 days
while IFS= read -r d; do [ -z "$d" ] || need "Delivery: $d"; done < <(DELIVERY=$delivery python3 -I -c '
import json, os
for e in json.loads(os.environ["DELIVERY"] or "{}").get("problems", []):
    if e["delivered_since"]: continue
    k = e["refused"] + e["held"]
    verb = "refused" if e["refused"] else "held back"
    code = " (" + e["code"] + ")" if e["code"] else ""
    print(e["provider"], verb, k, "message" if k == 1 else "messages", end="")
    print(code + ", and nothing has reached them since: the daily report says what it means and what to do")' 2>/dev/null)

# ---- what the installer is still waiting for (its last run)
if [ -s /var/lib/wombat-email/waiting.txt ]; then
    here_ok=$(runuser -u postgres -- psql -X -q -At -d wombat_email -c "SELECT value FROM settings WHERE key = 'backup_here_ok'" 2>/dev/null)
    while IFS= read -r w; do
        case $w in "backups are only on this server"*) [ "$here_ok" = yes ] && continue ;; esac   # the owner keeps them here
        need "Waiting: $w"
    done < /var/lib/wombat-email/waiting.txt
fi

# ---- yesterday's mail traffic (pflogsumm), kept for the panel's numbers; the email shows only its totals
since=$(date -d yesterday +%Y-%m-%d); until=$(date +%Y-%m-%d)
journalctl --since "$since" --until "$until" -o short -t postfix/smtpd -t postfix/smtp -t postfix/lmtp \
    -t postfix/cleanup -t postfix/qmgr -t postfix/bounce -t postfix/submission/smtpd -t postfix/submissions/smtpd \
    -t postfix/pickup -t postfix/local 2>/dev/null \
    | pflogsumm --problems-first --rej-add-from --verbose-msg-detail -q 2>/dev/null \
    | sed -n '1,/^message deferral detail/p' | head -120 > /var/lib/wombat-email/pflogsumm-latest.txt

# ---- the report, in that layout: == sections ==, one [ok] / [WARN] / [CRIT] line per check, the
# overall status last; what needs attention first, marked (new) when it wasn't there yesterday.
updates_n=$(apt-get -s upgrade 2>/dev/null | grep -c '^Inst ' || true)
updates_sec=$(apt-get -s upgrade 2>/dev/null | grep '^Inst ' | grep -c -- '-security' || true)
# The long values go to Python in files, not the environment: one variable over the kernel's 128 KB and Python
# can't start at all (as the weekly report found on bsdmail 2026-11-16).
we_in=$(mktemp -d)
printf '%s\n' "${attention[@]}" > "$we_in/ATTN"
/usr/local/libexec/wombat-email-logstats 1 --json > "$we_in/STATS" 2>/dev/null || echo '{}' > "$we_in/STATS"
printf '%s' "$delivery" > "$we_in/DELIVERY"
WE_IN=$we_in HOST=$host DISK=$disk QUEUE=$queue B_MSG=$b_msg B_AGE=$b_age \
UPDATES=$updates_n UPDATES_SEC=$updates_sec WE_MINE=$we_mine WE_LATEST=$we_latest RSPAMD_INST=${inst%%-*} \
python3 -I - <<'PY' > /var/lib/wombat-email/report-latest.txt
import glob, json, os, re, shutil, subprocess, sys, textwrap, time
sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share
E = dict(os.environ)
for k in ("ATTN", "STATS", "DELIVERY"):
    try: E[k] = open(os.path.join(E["WE_IN"], k), encoding="utf-8", errors="replace").read()
    except OSError: E[k] = ""
attn = [a for a in E["ATTN"].split("\n") if a]
st = json.loads(E["STATS"] or "{}")
def n(x): return f"{x:,}"
def run(cmd): return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout
# Which findings are critical (mail is or soon will be affected); the rest are warnings.
CRIT = ("Service ", "Disk ", "Backup", "Nightly mail test")
def level(a):
    if a.startswith("Certificate ") and re.search(r"expires in ([0-9]|-)\d* days", a) and int(re.search(r"in (-?\d+) days", a)[1]) < 7: return "CRIT"
    if a.startswith("Private mailbox ") and "waits in the queue" in a: return "CRIT"   # its mail isn't arriving
    return "CRIT" if a.startswith(CRIT) else "WARN"
out, worst = [], "OK"
def mark(kind, text):
    global worst
    if kind == "CRIT" or (kind == "WARN" and worst == "OK"): worst = kind
    out.append(f"  [{'ok' if kind == 'OK' else kind}]{' ' * (3 if kind == 'OK' else 1)}{text}")
def section(title): out.extend(["", f"== {title} =="])
def has(*p): return [a for a in attn if a.startswith(p)]
# Each check's state in a few words, compared with yesterday's for "Changed since yesterday" (short:
# "Ubuntu updates: 4 waiting → none waiting"). Counts that differ every day aren't checks, so they aren't here.
now = {}
def track(label, value): now[label] = value

out.append(f"{E['HOST']} daily status report - {time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
out.append("=" * len(out[0]))   # as long as the title line
state_file = "/var/lib/wombat-email/report-state.json"
try: before = set(json.load(open(state_file)).get("attention", []))
except Exception: before = set()
needs = [a for a in attn if not a.startswith("Waiting: ")]
if needs:
    section("Needs attention")
    for a in needs: mark(level(a), a)
changes_at = len(out)   # "Changed since yesterday" goes here, once everything is known

section("Service status")
php = sorted(os.path.basename(p)[:-8] for p in glob.glob("/lib/systemd/system/php*-fpm.service"))
for svc in ["postfix", "dovecot", "postgresql", "rspamd", "redis-server", "clamav-daemon", "unbound", "fail2ban", "apache2", *php[-1:], "ufw"]:
    ok = subprocess.run(["systemctl", "is-active", "--quiet", svc]).returncode == 0
    mark("OK" if ok else "CRIT", f"{svc}: {'active' if ok else 'NOT active'}")
    track(svc, "active" if ok else "NOT active")

section("Disk usage")
du = shutil.disk_usage("/")
g = lambda b: f"{b / 1e9:.0f}G" if b >= 1e10 else f"{b / 1e9:.1f}G"
mark("WARN" if has("Disk ") else "OK", f"/: {E['DISK']}% used ({g(du.used)} of {g(du.total)})")
track("Disk", f"{E['DISK']}% full" if has("Disk ") else "fine")
store = run("du -sh /var/mail/vmail 2>/dev/null").split()
out.append(f"  mail store (/var/mail/vmail): {store[0] if store else 'unknown'}")

section("Updates")
u, us = int(E["UPDATES"] or 0), int(E["UPDATES_SEC"] or 0)
mark("OK", "Ubuntu: none waiting" if u == 0 else f"Ubuntu: {u} waiting ({us} security; those install by themselves)")
track("Ubuntu updates", "none waiting" if u == 0 else f"{u} waiting")
track("Restart", "needed" if os.path.exists("/var/run/reboot-required") else "not needed")
if os.path.exists("/var/run/reboot-required"): mark("WARN", "a restart finishes an update: panel › Settings › Restart")
latest = E.get("WE_LATEST", "")
mark("WARN" if has("Wombat-Email") else "OK", f"Wombat-Email v{E['WE_MINE']}" + (f"; v{latest} is available" if has("Wombat-Email") else ", the newest" if latest else ""))
for a in has("Webmail"): mark("WARN", a)
track("Wombat-Email", f"v{E['WE_MINE']}")

section("Backup")
age = int(E["B_AGE"])
mark("CRIT" if has("Backup") else "OK", E["B_MSG"] + (f" ({age} hours ago)" if age >= 0 else ""))
track("Backup", E["B_MSG"] if has("Backup") else "snapshot saved")

section("Mail")
q = int(E["QUEUE"] or 0)
mark("WARN" if q >= 50 else "OK", f"Postfix queue: {q} message{'' if q == 1 else 's'}")
track("Mail queue", f"{q} waiting" if q >= 50 else "fine")

mark("CRIT" if has("Nightly mail test") else "OK", "nightly mail test " + ("FAILED" if has("Nightly mail test") else "passed"))
track("Mail test", "failed" if has("Nightly mail test") else "passed")
rows = we.pflog_rows(open("/var/lib/wombat-email/pflogsumm-latest.txt").read())
w = max(len(r[0]) for r in rows)
out += [f"    {v:>{w}}  {label}" for v, label in rows]

section("Delivery to the big providers (last 24 hours)")
dl = json.loads(E.get("DELIVERY") or "{}")
probs = dl.get("problems", [])
if not probs: mark("OK", "nothing refused or held back by their block lists or checks")
for e in probs:
    k = e["refused"] + e["held"]
    what = f"{e['provider']} {'refused' if e['refused'] else 'held back'} {k} message{'s' if k != 1 else ''}" + (f" ({e['code']})" if e["code"] else "")
    cleared = e["delivered_since"] > 0
    mark("OK" if cleared else "WARN", what + (f"; {e['delivered_since']} delivered to them since, so it cleared" if cleared else "; nothing has reached them since"))
    # what to do: now, or (it cleared) if it comes back, without pointing at the refusal it doesn't show then
    todo = e["todo"]
    if cleared:
        todo = re.sub(r",? (giving|with) (your server's address and )?the refusal below", "", todo)
        todo = todo if todo.startswith("If ") else "If it keeps happening: " + todo[:1].lower() + todo[1:]
    else:
        todo = todo.removeprefix("If it keeps happening, ")
        todo = "What to do: " + todo[:1].lower() + todo[1:]
    more = [e["means"], todo + (f" {e['link']}" if e["link"] else "")]
    if not cleared:
        more += [f"Your server's address: {dl.get('ip', '')}", f"The refusal: {e['sample']}"]
    for para in more:
        out.extend("         " + l for l in textwrap.wrap(para, 90))
    track(f"Delivery to {e['provider']}", "cleared" if cleared else "refused")

section("Rspamd")
sp = st.get("spam", {})
learned = re.search(r"Messages learned: (\d+)", run("rspamc stat 2>/dev/null"))
mark("WARN" if has("Rspamd update") else "OK", f"Rspamd {E.get('RSPAMD_INST', '')}" + (": an update is waiting" if has("Rspamd update") else ""))
track("Rspamd", E.get("RSPAMD_INST", ""))
scanned = sum(sp.values()) if sp else 0
rows = [("scanned", scanned), ("rejected", sp.get("reject", 0)), ("to Spam folders", sp.get("add header", 0)),
        ("clean", sp.get("no action", 0)), ("viruses refused", st.get("viruses", 0))]
w = max(len(n(v)) for _, v in rows)
for label, v in rows:
    if v or label in ("scanned", "clean"): out.append(f"    {n(v):>{w}}  {label}")
if learned and int(learned[1]): out.append(f"    {int(learned[1]):,} messages learned so far")

section("ClamAV")
fc = run("grep -h 'daily.c[lv]d updated' /var/log/clamav/freshclam.log 2>/dev/null | tail -1").strip()
m = re.match(r"(\w{3} \w{3} +\d+ [\d:]+ \d{4})", fc)
when = time.mktime(time.strptime(m[1].replace("  ", " "), "%a %b %d %H:%M:%S %Y")) if m else 0
v = re.search(r"version: (\d+)", fc)
mark("OK" if when and time.time() - when < 3 * 86400 else "WARN",
     f"virus signatures updated {time.strftime('%b %-d %H:%M', time.localtime(when))}" + (f" (daily {v[1]})" if v else "") if when else "no signature update found in freshclam's log")
track("Virus signatures", "current" if when and time.time() - when < 3 * 86400 else "out of date")

section("SSL certificates")
certs = we.certificates()
for days, name, end in [c for c in certs if c[0] < 21]: mark("CRIT" if days < 7 else "WARN", f"{name}: expires in {days} days (renewal isn't working)")
if certs:
    days, name, end = certs[0]
    if days >= 21: mark("OK", f"{len(certs)} certificate{'' if len(certs) == 1 else 's'} valid, the soonest ends in {days} days ({time.strftime('%Y-%m-%d', end)})")
else: mark("WARN", "no certificates yet")
soon = [c for c in certs if c[0] < 21]
track("Certificates", f"{len(certs)} valid" if certs and not soon else ", ".join(f"{c[1]} ends in {c[0]} days" for c in soon) or "none")

section("Security (fail2ban)")
for jail in [j.strip() for j in run("fail2ban-client status 2>/dev/null").split("Jail list:")[-1].split(",") if j.strip()]:
    s = run(f"fail2ban-client status {jail} 2>/dev/null")
    cur, tot = re.search(r"Currently banned:\s*(\d+)", s), re.search(r"Total banned:\s*(\d+)", s)
    mark("OK", f"{jail}: currently banned {cur[1] if cur else '?'}, total banned {tot[1] if tot else '?'}")
sf, mf = st.get("ssh", {}), st.get("mail_fail", {})
imap = st.get("imap", {})
apps = sum(c for x in imap.values() for h, c in x.items() if h != "webmail")
web = sum(c for x in imap.values() for h, c in x.items() if h == "webmail")
out.append(f"  logins: SSH {sum(sf.get('ok', {}).values())}, mail apps {n(apps)}, webmail {n(web)}, panel {st.get('panel', {}).get('ok', 0)}")
out.append(f"  failed: SSH {n(sf.get('fail', 0))}, mail {n(mf.get('n', 0))}, panel {st.get('panel', {}).get('fail', 0)}")

section("PostgreSQL Mail database")
sql = lambda q: run(f"runuser -u postgres -- psql -X -At -d wombat_email -c \"{q}\" 2>/dev/null").strip()
counts = sql("SELECT (SELECT count(*) FROM domains) || '|' || (SELECT count(*) FROM mailboxes WHERE NOT relay) || '|' || (SELECT count(*) FROM mailboxes WHERE relay) || '|' || (SELECT count(*) FROM aliases WHERE NOT system) || '|' || (SELECT count(*) FROM admins)").split("|")
if len(counts) == 5: mark("OK", f"domains: {counts[0]} | mailboxes: {counts[1]} | relays: {counts[2]} | aliases: {counts[3]} | panel admins: {counts[4]}")
else: mark("CRIT", "couldn't read the mail database")

section("DNS sanity")
domains = [d for d in sql("SELECT name FROM domains WHERE enabled AND mail_here ORDER BY name").split("\n") if d]
dig = lambda name, t: run(f"dig +short {t} {name} @127.0.0.1 2>/dev/null").strip()
host = E["HOST"]
for check, test in (("MX", lambda d: host + "." in dig(d, "MX")),
                    ("DKIM", lambda d: "p=" in dig(f"wombat._domainkey.{d}", "TXT")),
                    ("DMARC", lambda d: "v=DMARC1" in dig(f"_dmarc.{d}", "TXT"))):
    bad = [d for d in domains if not test(d)]
    track(check, "missing for " + ", ".join(bad) if bad else "fine")
    mark("WARN" if bad else "OK", f"{check}: " + ("missing or wrong for " + ", ".join(bad) if bad else ("1 domain" if len(domains) == 1 else f"all {len(domains)} domains") + (f" → {host}" if check == "MX" else "")))
ip = run("hostname -I").split()
ptr = dig(ip[0], "-x").rstrip(".") if ip else ""
mark("OK" if ptr == host else "WARN", f"Reverse DNS: {ptr or 'none'}" + ("" if ptr == host else f" (should be {host})"))
track("Reverse DNS", ptr or "none")

try: was = json.load(open(state_file)).get("checks", {})
except Exception: was = {}
moved = [(k, was[k], v) for k, v in now.items() if k in was and was[k] != v]
if moved:
    w = max(len(k) for k, _, _ in moved) + 1
    out[changes_at:changes_at] = ["", "== Changed since yesterday =="] + [f"  {k + ':':<{w}} {a} → {b}" for k, a, b in moved]

waits = [a[len("Waiting: "):] for a in attn if a.startswith("Waiting: ")]
if waits:
    section("Still waiting (not failures; each run checks again)")
    out += [f"  - {x}" for x in waits]

out += ["", "=" * len(out[0]), f"Overall status: {worst}"]
print("\n".join(out))
json.dump({"attention": attn, "status": worst, "checks": now}, open(state_file + ".new", "w"))   # kept once mailed
PY
report_rc=$?
rm -rf "$we_in"

# The same findings, and the details behind them, for the panel (it can't read certificates, apt or
# mailbox sizes itself). Mailbox sizes name addresses, so they go in their own file only the panel reads.
ATTN=$(printf '%s\n' "${attention[@]}") WE_LATEST=$we_latest python3 -I - <<'PY'
import glob, os, re, subprocess, sys, time
sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share
certs = []
for c in sorted(glob.glob("/etc/letsencrypt/live/*/fullchain.pem")):
    end = we.cert_end(c)
    days = we.cert_days(end) if end else -1
    san = subprocess.run(["openssl", "x509", "-in", c, "-noout", "-ext", "subjectAltName"], capture_output=True, text=True).stdout
    name = os.path.basename(os.path.dirname(c))
    try:
        method = re.search(r"^authenticator\s*=\s*(\S+)", open(f"/etc/letsencrypt/renewal/{name}.conf").read(), re.M).group(1)
    except (OSError, AttributeError):
        method = ""
    certs.append({"name": name, "days": days, "expires": int(time.time()) + days * 86400, "method": method,
                  "names": sorted(x[4:] for x in san.replace(",", " ").split() if x.startswith("DNS:"))})
def ver(cmd):
    return subprocess.run(cmd, capture_output=True, text=True, shell=True).stdout.strip().split("-")[0]
def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True, shell=True).stdout
ufw = run("ufw status verbose")
ssh = dict(l.split(" ", 1) for l in run("sshd -T 2>/dev/null").splitlines() if " " in l)
jails = run("fail2ban-client status 2>/dev/null").split("Jail list:")[-1].strip()
sim = run("apt-get -s upgrade 2>/dev/null")
packages = [{"name": m[1], "installed": m[2], "available": m[3], "security": "-security" in m[4]}
            for m in re.finditer(r"^Inst (\S+) \[([^\]]+)\] \((\S+) ([^)]*)\)", sim, re.M)]
report = open("/var/lib/wombat-email/pflogsumm-latest.txt").read()
def total(label): return we.pflog_total(report, label)
usage = {}
for line in run("doveadm quota get -A 2>/dev/null").splitlines():
    f = line.split()
    if len(f) >= 7 and f[-4] in ("STORAGE", "MESSAGE"):
        usage.setdefault(f[0], {})[f[-4].lower()] = int(f[-3])
s = {"checked": int(time.time()), "attention": [a for a in os.environ.get("ATTN", "").split("\n") if a],
     "firewall": {"active": "Status: active" in ufw,
                  "open": sorted({l.split()[0].split("/")[0] for l in ufw.splitlines() if " ALLOW IN " in l and "(v6)" not in l})},
     "ssh": {k: ssh.get(k, "") for k in ("passwordauthentication", "permitrootlogin", "kbdinteractiveauthentication")},
     "fail2ban": [j.strip() for j in jails.split(",") if j.strip()],
     "updates": {"pending": sum(1 for l in sim.splitlines() if l.startswith("Inst ")),
                 "security": sum(1 for l in sim.splitlines() if l.startswith("Inst ") and "-security" in l),
                 "packages": packages},
     "restart_needed": os.path.exists("/var/run/reboot-required"),
     "mail": {k: total(k) for k in ("received", "delivered", "deferred", "bounced", "rejected")},
     "versions": {n: ver(f"dpkg-query -W -f='${{Version}}' {p} 2>/dev/null").split(":")[-1].split("+")[0]
                  for n, p in (("Postfix", "postfix"), ("Dovecot", "dovecot-core"), ("Rspamd", "rspamd"), ("ClamAV", "clamav-daemon"),
                               ("PostgreSQL", "postgresql"), ("Redis", "redis-server"), ("Apache", "apache2"))},
     "system": dict(l.rstrip().split("=", 1) for l in open("/etc/os-release") if "=" in l).get("PRETTY_NAME", "").strip('"'),
     "certificates": certs,
     "wombat_latest": os.environ.get("WE_LATEST", ""),
     "rspamd": {"installed": ver("dpkg-query -W -f='${Version}' rspamd 2>/dev/null"),
                "candidate": ver("apt-cache policy rspamd 2>/dev/null | awk '/Candidate:/ {print $2}'")}}
we.write_json("/var/lib/wombat-email/mailbox-usage.json", {"checked": int(time.time()), "mailboxes": usage}, mode=0o640, group="wombat-panel")
we.write_json("/var/lib/wombat-email/status.json", s, indent=1)
PY

state=/var/lib/wombat-email/report-state.json
overall=$(python3 -I -c 'import json, sys; print(json.load(open(sys.argv[1]))["status"])' "$state.new" 2>/dev/null)
if [ "$report_rc" -ne 0 ] || [ ! -s /var/lib/wombat-email/report-latest.txt ] || [ -z "$overall" ]; then
    # Never an empty "OK": the report says it failed, and how to see why.
    overall=FAILED
    printf '%s daily status report - %s\n\nThe report could not be made (exit %s). Run wombat-email-report --print as root to see why.\n' \
        "$host" "$(date '+%F %T %Z')" "$report_rc" > /var/lib/wombat-email/report-latest.txt
    rm -f "$state.new"
fi
keep_state() { [ "$MAILING" = 1 ] && [ -f "$state.new" ] && mv -f "$state.new" "$state"; rm -f "$state.new"; }
subject="[$host] Daily status: $overall - $(date +%F)"
REPORT_TO=${REPORT_TO:-${ADMIN_EMAIL:-}}
if [ $PRINT = 1 ] || [ -z "$REPORT_TO" ]; then
    echo "Subject: $subject"; echo; cat /var/lib/wombat-email/report-latest.txt
    keep_state
    [ "$overall" != FAILED ]; exit   # the installer's check after it (95-report) sees a failed report
fi
. /usr/local/lib/wombat-email/common.sh   # mail_head, mail_send
message() { mail_head "$REPORT_TO" "$subject"; cat /var/lib/wombat-email/report-latest.txt; }
# Plain text plus the same text as fixed-width HTML (wombat-email-mime, installed by 60-dovecot).
if [ "${1:-}" = --message ]; then message | /usr/local/libexec/wombat-email-mime; keep_state; exit 0; fi   # the whole message, for checking
message | mail_send "$REPORT_TO" && keep_state
