#!/bin/bash
# Wombat-Email: the weekly report, Mondays at 06:15 (laid out with the owner 2026-11-04, like the daily) (installed by installer/95-report.sh as
# /usr/local/sbin/wombat-email-weekly, run by wombat-email-weekly.timer). The lists behind the daily
# glance's numbers, for the last seven days: mail sent per user and received per mailbox, logins and where
# from, failed logins and bans, refused mail, Rspamd's verdicts, what robots tried on the web (as
# a mail server's weekly usage report and logwatch do), then every certificate, the updates installed,
# and the mailboxes' sizes. Mailed like the daily report.
#   wombat-email-weekly --print     to the screen instead
set -uo pipefail
. /etc/wombat-email/settings
host=$(hostname -f)
from=$(date -d "7 days ago" '+%b %-d'); to=$(date -d yesterday '+%b %-d')

report() {
    # What the report reads goes to Python in files, not the environment: a busy server's week of pflogsumm
    # outgrows the kernel's 128 KB limit for one variable, and Python then can't start at all (bsdmail 2026-11-16).
    local t rc; t=$(mktemp -d) || return 1
    # The week's Postfix log through pflogsumm: totals, per day, per hour, and who sent mail here.
    journalctl --since "$(date -d "7 days ago" +%F)" --until "$(date +%F)" -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 -q > "$t/PFLOG" 2>/dev/null
    { runuser -u postgres -- psql -X -At -d wombat_email -c "SELECT name FROM domains" 2>/dev/null; hostname -d; } > "$t/OURS"
    /usr/local/libexec/wombat-email-logstats 7 --json > "$t/STATS" 2>/dev/null || echo '{}' > "$t/STATS"
    doveadm quota get -A > "$t/QUOTA" 2>/dev/null
    WE_IN=$t HOST=$host python3 -I - <<'PY'
import datetime, glob, gzip, json, os, re, 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 ("PFLOG", "OURS", "STATS", "QUOTA"):
    try: E[k] = open(os.path.join(E["WE_IN"], k), encoding="utf-8", errors="replace").read()
    except OSError: E[k] = ""
st = json.loads(E["STATS"] or "{}")
def n(x): return f"{x:,}"
out = []
def section(title): out.extend(["", f"== {title} =="])
def counts(rows, more=0, indent=4):
    """Right-aligned counts and their labels; rows = [(count, label)]."""
    if not rows: out.append(" " * indent + "none"); return
    w = max(len(n(c)) for c, _ in rows)
    out.extend(f"{' ' * indent}{n(c):>{w}}  {label}" for c, label in rows)
    if more: out.append(f"{' ' * indent}{'':>{w}}  … and {n(more)} more")
def top(pairs, k=10): return pairs[:k], max(0, len(pairs) - k)

title = f"{E['HOST']} weekly report - {st.get('from', '?')} to {st.get('to', '?')}"
out += [title, "=" * len(title)]

# ---- the week's mail as a whole (pflogsumm), drawn across
pf = E.get("PFLOG", "")
def block(head):
    m = re.search(rf"^{re.escape(head)}.*?\n-+\n(.*?)(?:\n\n|\Z)", pf, re.S | re.M)
    return m[1].splitlines() if m else []
section("Mail")
rows = we.pflog_rows(pf)
wd = max(len(r[0]) for r in rows)
out.extend(f"    {v:>{wd}}  {label}" for v, label in rows)

days = []
for l in block("Per-Day Traffic Summary"):
    m = re.match(r"\s*(\w{3})\s+(\d+) (\d{4})\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)", l)
    if m: days.append((datetime.date(int(m[3]), datetime.datetime.strptime(m[1], "%b").month, int(m[2])), *map(int, m.groups()[3:])))
if days:
    section("Mail by day")
    cw = max(6, max(len(n(v)) for d in days for v in d[1:]) + 1)
    out.append(" " * 14 + "".join(f"{d[0].strftime('%a'):>{cw}}" for d in days))
    out.append(" " * 14 + "".join(f"{d[0].strftime('%-m/%-d'):>{cw}}" for d in days))
    for i, label in ((1, "received"), (2, "delivered"), (5, "rejected")):
        out.append(f"  {label:<12}" + "".join(f"{n(d[i]):>{cw}}" for d in days))

hours = [list(map(int, re.findall(r"\d+", l)[2:])) for l in block("Per-Hour Traffic Daily Average") if re.match(r"\s*\d{4}-\d{4}", l)]
if len(hours) == 24:
    section("Mail by hour (average day)")
    bars = "▁▂▃▄▅▆▇█"
    out.append(" " * 14 + "0     6     12    18   23")
    out.append(" " * 14 + "|     |     |     |    |")
    for i, label in ((0, "received"), (4, "rejected")):
        vals = [h[i] for h in hours]
        top_ = max(vals) or 1
        pk = max(range(24), key=lambda k: vals[k])
        line = "".join(bars[min(7, round(v / top_ * 7))] if v else " " for v in vals)
        out.append(f"  {label:<12}{line}" + (f"  most at {pk:02d}:00 ({vals[pk]}/hour)" if vals[pk] else "  none"))

ours = {d.strip().lower() for d in E.get("OURS", "").split() if d.strip()}
senders = []
for l in block("Host/Domain Summary: Messages Received"):
    m = re.match(r"\s*(\d+)\s+(\d+)([km]?)\s+(\S+)$", l)
    if m and not any(m[4].lower() == d or m[4].lower().endswith("." + d) for d in ours):
        senders.append((int(m[1]), m[4]))
if senders:
    section("Mail from outside, by domain")
    rows, more = top(sorted(senders, key=lambda r: -r[0]))
    counts(rows, more)

section("Mail sent")
rows, more = top(sorted(((v["n"], f"{u} ({', '.join(v['hosts'][:3])}{', …' if len(v['hosts']) > 3 else ''})") for u, v in st.get("sent", {}).items()), key=lambda r: -r[0]))
counts(rows, more)

section("Mail received")
rows, more = top(sorted(((c, u) for u, c in st.get("received", {}).items()), key=lambda r: -r[0]))
counts(rows, more)

section("Mail app logins")
imap = st.get("imap", {})
rows, more = top(sorted(((sum(h.values()), f"{u} ({', '.join(f'{k} {v}x' for k, v in sorted(h.items(), key=lambda x: -x[1])[:3])})") for u, h in imap.items()), key=lambda r: -r[0]))
counts(rows, more)

section("SSH")
ssh = st.get("ssh", {})
# Logins per account and method: "root (publickey)", from one address or from several.
groups = {}
for k, c in ssh.get("ok", {}).items():
    who, _, ip = k.rpartition(" from ")
    g = groups.setdefault(who or k, [0, set()])
    g[0] += c
    if ip: g[1].add(ip)
counts(sorted(((c, f"{who} from " + (next(iter(ips)) if len(ips) == 1 else f"{len(ips)} addresses")) for who, (c, ips) in groups.items()), key=lambda r: -r[0]))
out.append(f"  failed: {n(ssh.get('fail', 0))} from {n(ssh.get('fail_from', 0))} addresses; the most:")
rows, _ = top([(c, ip) for ip, c in ssh.get("top", [])])
counts(rows, indent=6)

section("Failed mail logins")
mf = st.get("mail_fail", {})
out.append(f"  {n(mf.get('n', 0))} from {n(mf.get('from', 0))} addresses; the most:")
counts(top([(c, ip) for ip, c in mf.get("top", [])])[0], indent=6)
if mf.get("users"):
    out.append("  names they tried:")
    counts(top([(c, u) for u, c in mf["users"]])[0], indent=6)

section("Panel")
pn = st.get("panel", {})
out.append(f"  sign-ins: {n(pn.get('ok', 0))}, failed: {n(pn.get('fail', 0))}" + (" (" + ", ".join(f"{ip} {c}x" for ip, c in pn.get("top", [])[:3]) + ")" if pn.get("top") else ""))

section("Security (fail2ban)")
b = st.get("bans", {})
out.append(f"  bans: {n(b.get('n', 0))}" + (" (" + ", ".join(f"{j} {c}" for j, c in sorted(b.get("jails", {}).items(), key=lambda x: -x[1])) + ")" if b.get("jails") else ""))
if b.get("top"):
    out.append("  banned most often:")
    counts(top([(c, ip) for ip, c in b["top"]])[0], indent=6)

section("Mail refused")
rf = st.get("refused", {})
out.append(f"  {n(rf.get('n', 0))} refused; why:")
counts([(c, why) for why, c in rf.get("why", [])], indent=6)

section("Rspamd")
sp = st.get("spam", {})
rows = [(sum(sp.values()), "scanned"), (sp.get("reject", 0), "rejected"), (sp.get("add header", 0), "to Spam folders"),
        (sp.get("no action", 0), "clean"), (st.get("viruses", 0), "viruses refused")]
counts([r for r in rows if r[0] or r[1] in ("scanned", "clean")])

section("Web (panel and webmail)")
w = st.get("web", {})
out.append(f"  {n(w.get('requests', 0))} requests, {n(w.get('refused', 0))} refused (mostly robots); tried most:")
counts(top([(c, p) for p, c in w.get("top", [])])[0], indent=6)
if w.get("from"):
    out.append("  from:")
    counts(top([(c, ip) for ip, c in w["from"]])[0], indent=6)

section("SSL certificates")
certs = [(days, name, time.strftime("%Y-%m-%d", end)) for days, name, end in we.certificates()]
for days, name, until in [c for c in certs if c[0] < 21]: out.append(f"  [WARN] {name}: {days} days left ({until}); renewal isn't working")
if certs and certs[0][0] >= 21: out.append(f"  [ok]   {len(certs)} certificate{'' if len(certs) == 1 else 's'} valid, the soonest ends in {certs[0][0]} days ({certs[0][2]})")
if not certs: out.append("    none")

section("Updates installed")
since = (datetime.date.today() - datetime.timedelta(days=7)).isoformat()
until = datetime.date.today().isoformat()
days = {}
for path in sorted(glob.glob("/var/log/apt/history.log*"), reverse=True):
    text = (gzip.open if path.endswith(".gz") else open)(path, "rt", errors="replace").read()
    for block in text.split("\n\n"):
        m = re.search(r"^Start-Date: (\S+)", block, re.M)
        k = re.search(r"^Upgrade: (.*)$", block, re.M)   # updates only: new installs aren't updates
        if m and k and since <= m[1] < until:
            days.setdefault(m[1], set()).update(re.findall(r"([^\s:,]+)(?::\S+)? \(", k[1]))
if not days: out.append("    none")
for day in sorted(days):
    pk = sorted(days[day])
    lines = textwrap.wrap(", ".join(pk), 60, break_on_hyphens=False)
    out.append(f"  {day}  {len(pk)}: {lines[0]}")
    out.extend(f"  {'':10}  {'':>{len(str(len(pk)))}}  {l}" for l in lines[1:])

section("Mailboxes")
sizes = []
for line in E.get("QUOTA", "").splitlines():
    f = line.split()
    if len(f) >= 7 and f[-4] == "STORAGE": sizes.append((int(f[-3]), f[0]))
empty = sum(1 for v, _ in sizes if v == 0)   # relay accounts (websites) and unused mailboxes
sizes = sorted((x for x in sizes if x[0] > 0), reverse=True)
def kb(v): return f"{v / 1024 / 1024:.1f} GB" if v >= 1024 * 1024 else f"{v / 1024:.1f} MB" if v >= 1024 else f"{v} KB"
rows = [(kb(v), u) for v, u in sizes[:30]]
if rows:
    wd = max(len(r[0]) for r in rows)
    out.extend(f"    {s:>{wd}}  {u}" for s, u in rows)
    if len(sizes) > 30: out.append(f"    {'':>{wd}}  … and {len(sizes) - 30} more")
    if empty: out.append(f"    {'':>{wd}}  … and {empty} empty")
else: out.append("    none" + (f" with mail ({empty} empty)" if empty else ""))

out += ["", "=" * len(title)]
print("\n".join(out))
PY
    rc=$?
    rm -rf "$t"
    return $rc
}

if [ "${1:-}" = --print ]; then report; exit; fi
to_addr=${REPORT_TO:-${ADMIN_EMAIL:-}}
[ -n "$to_addr" ] || exit 0
. /usr/local/lib/wombat-email/common.sh   # mail_head, mail_send
{
    mail_head "$to_addr" "[$host] Weekly report - $(date -d "7 days ago" +%F) to $(date -d yesterday +%F)"
    # never an empty report: if it couldn't be made, the mail says so and where to look
    errf=$(mktemp); body=$(report 2>"$errf"); rc=$?; err=$(tail -c 2000 "$errf"); rm -f "$errf"
    [ -z "$err" ] || echo "$err" >&2   # into the journal, as before
    if [ "$rc" != 0 ] || [ -z "${body//[[:space:]]/}" ]; then
        echo "The weekly report couldn't be made this time (exit $rc)."
        echo "What it said: ${err:-nothing}"
        echo "Run wombat-email-weekly --print as root to see it; journalctl -t wombat-email-weekly has the log."
    else
        printf '%s\n' "$body"
    fi
} | mail_send "$to_addr"
