#!/bin/bash
# Wombat-Email: the allow and block lists, for Rspamd (installed by installer/70-spam.sh as
# /usr/local/sbin/wombat-email-senders; docs/spam-and-senders.md). Run as root by
# wombat-email-senders.path when the panel changes a list (requests/senders), someone pressed "Not spam"
# on a daily summary's link (requests/not-spam-KEY, with requests/senders), or a mailbox moved a message out
# of Spam (a file in /var/lib/wombat-email/moved/), and by every installer run.
#  1. Each "moved out of Spam" file (MAILBOX<tab>FROM, written by the learn script as vmail) is read as
#     data, checked, and becomes an allow entry for that mailbox and address (source "moved"). An entry
#     already there for that value is left as it is.
#  2. The maps Rspamd reads are written from the database: senders.map (SCOPE<tab>KIND<tab>VALUE) and
#     aliases.map (ADDRESS<space>MAILBOX[,MAILBOX...], every mailbox to itself too). Rspamd reloads
#     them by itself when they change; nothing restarts.
set -euo pipefail
MOVED=/var/lib/wombat-email/moved
MAPS=/var/lib/wombat-email/rspamd
LOG=/var/log/wombat-email/senders.log
exec 9>/run/wombat-email-senders.lock
flock 9
rm -f /var/lib/wombat-email/requests/senders
sql() { runuser -u postgres -- psql -X -q -At -v ON_ERROR_STOP=1 -d wombat_email "$@"; }
log() { echo "$(date -Is) $*" >> "$LOG"; }

# ---- 1. moves out of Spam (a hidden name is one still being written; one left over from a crash goes)
find "$MOVED" -maxdepth 1 -name '.m.*' -mmin +5 -delete 2>/dev/null || true
for f in "$MOVED"/*; do
    [ -f "$f" ] && [ ! -L "$f" ] || continue
    line=$(head -c 600 "$f" | head -1 | tr -d '\r'); rm -f "$f"
    mbox=${line%%$'\t'*}; from=${line#*$'\t'}
    mbox=${mbox,,}; from=${from,,}
    [[ "$mbox" =~ ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}$ ]] || { log "moved: skipped, not a mailbox: ${mbox:0:80}"; continue; }
    [[ "$from" =~ ^[a-z0-9._%+=-]+@[a-z0-9.-]+\.[a-z]{2,63}$ ]] || { log "moved: $mbox: skipped, no usable From"; continue; }
    [ "${#from}" -le 254 ] || continue
    added=$(sql -v m="$mbox" -v v="$from" <<'SQL'
INSERT INTO sender_rules (domain_id, mailbox_id, kind, value, source, added_by)
SELECT domain_id, id, 'allow', :'v', 'moved', :'m' FROM mailboxes WHERE email = :'m'
ON CONFLICT DO NOTHING RETURNING id;
SQL
)
    if [ -n "$added" ]; then
        log "moved: $mbox allows $from"
        sql -v d="$mbox allows $from (moved a message out of Spam)" <<<"INSERT INTO admin_log (action, detail) VALUES ('sender allowed', :'d');" || true
    fi
done

# ---- 1b. "Not spam" pressed on a summary's link (panel/public/not-spam.php): the panel marked the link
# used and left requests/not-spam-KEY. The message is learned as not spam (the mailbox's own Bayes and the
# shared one), moved to the inbox, and its sender allowed for that mailbox (source "not-spam"). The result
# goes back to the link's row, where the page reads it.
for f in /var/lib/wombat-email/requests/not-spam-*; do
    [ -f "$f" ] && [ ! -L "$f" ] || continue
    key=${f##*/not-spam-}; rm -f "$f"
    [[ "$key" =~ ^[A-Za-z0-9_-]{22}$ ]] || continue
    row=$(sql -F $'\t' -v k="$key" <<'SQL'
SELECT m.email, l.mailbox_guid, l.uid, l.sender, l.mailbox_id, m.domain_id FROM summary_links l JOIN mailboxes m ON m.id = l.mailbox_id
WHERE l.key = :'k' AND l.kind = 'not-spam' AND l.used_at IS NOT NULL AND l.result = '';
SQL
)
    [ -n "$row" ] || continue
    IFS=$'\t' read -r mbox guid uid sender mid did <<<"$row"
    [[ "$guid" =~ ^[0-9a-f]{32}$ && "$uid" =~ ^[0-9]+$ ]] || continue
    if [ -n "$(doveadm search -u "$mbox" mailbox Spam mailbox-guid "$guid" uid "$uid" 2>/dev/null)" ]; then
        doveadm fetch -u "$mbox" text mailbox-guid "$guid" uid "$uid" 2>/dev/null | tail -n +2 \
            | rspamc -h 127.0.0.1:11334 -d "$mbox" learn_ham >/dev/null 2>&1 || true
        doveadm move -u "$mbox" INBOX mailbox-guid "$guid" uid "$uid" && result=moved || result=gone
        if [ $result = moved ] && [[ "$sender" =~ ^[a-z0-9._%+=-]+@[a-z0-9.-]+\.[a-z]{2,63}$ ]]; then
            sql -v d="$did" -v m="$mid" -v v="$sender" -v b="$mbox" >/dev/null <<'SQL'
INSERT INTO sender_rules (domain_id, mailbox_id, kind, value, source, added_by) VALUES (:d, :m, 'allow', :'v', 'not-spam', :'b')
ON CONFLICT DO NOTHING;
SQL
        fi
    else
        result=gone   # moved or deleted already
    fi
    sql -v k="$key" -v r="$result" <<<"UPDATE summary_links SET result = :'r' WHERE key = :'k';"
    sql -v d="$mbox: $sender ($result)" <<<"INSERT INTO admin_log (action, detail) VALUES ('not spam from the summary', :'d');" || true
    log "not spam: $mbox: $sender: $result"
done

# ---- 2. the maps
install -d -m 755 "$MAPS"
write() {   # NAME, content on stdin: replaced only when it differs (Rspamd watches the file)
    local new; new=$(mktemp "$MAPS/.$1.XXXXXX")
    cat > "$new"; chmod 644 "$new"
    if cmp -s "$new" "$MAPS/$1"; then rm -f "$new"; else mv -f "$new" "$MAPS/$1"; log "wrote $1 ($(grep -c . "$MAPS/$1" || true) lines)"; fi
}
sql <<'SQL' | write senders.map
SELECT coalesce(m.email, d.name, '*') || E'\t' || r.kind || E'\t' || r.value
FROM sender_rules r LEFT JOIN domains d ON d.id = r.domain_id LEFT JOIN mailboxes m ON m.id = r.mailbox_id
ORDER BY 1;
SQL
sql <<'SQL' | write aliases.map
SELECT source || ' ' || string_agg(destination, ',' ORDER BY destination) FROM aliases WHERE enabled GROUP BY source
UNION ALL
SELECT email || ' ' || email FROM mailboxes m WHERE NOT relay AND NOT EXISTS (SELECT 1 FROM aliases a WHERE a.source = m.email AND a.enabled)
ORDER BY 1;
SQL
