#!/usr/bin/python3 -I
# Wombat-Email: removes read receipt requests from arriving mail (installer/92-receipts.sh), so the
# reader's mail app never offers to tell the sender the message was opened. On unless Settings switches
# it off for the whole server, or Mailboxes keeps them for one mailbox; who keeps them is in KEEP.
#
#   wombat-email-receipts MAILBOX      message on stdin
#
# The new message on stdout and exit 0; nothing on stdout and exit 1 when it stays as it came (no
# request in it, or this mailbox keeps them); exit 2 when anything failed (it stays as it came too).
# Used by Dovecot's delivery filter (as vmail, with $USER) and by the private mailboxes' delivery
# (wombat-email-pgp-deliver, before it encrypts: the inside copy of the headers would keep them).
# Only the message's own headers change; a forwarded message inside it is left alone.
import os, re, sys

KEEP = '/var/lib/wombat-email/receipts/keep'
MAX = 64 * 1024 * 1024
# Disposition-Notification-To (RFC 8098) is the read receipt mail apps ask about; the others are older
# kinds some apps still send or honor.
ASKS = re.compile(rb'(disposition-notification-to|disposition-notification-options|return-receipt-to|'
                  rb'x-confirm-reading-to)[ \t]*:', re.I)


def keeps(box):
    try:
        with open(KEEP, 'rb') as f:
            names = {l.strip().lower() for l in f.read().decode('utf-8', 'replace').splitlines()}
    except FileNotFoundError:
        return False
    return '*' in names or box in names


def main():
    box = (sys.argv[1] if len(sys.argv) > 1 else os.environ.get('USER', '')).strip().lower()
    raw = sys.stdin.buffer.read(MAX + 1)
    if '@' not in box or len(raw) > MAX:
        return 1
    # the headers end at the first empty line (LF or CRLF)
    m = re.search(rb'\r?\n\r?\n', raw)
    head_end = m.start() if m else len(raw)
    head = raw[:head_end]
    if not ASKS.search(head) or keeps(box):
        return 1
    out, drop = [], False
    for line in re.split(rb'(?<=\n)', head):
        if line[:1] in (b' ', b'\t'):        # a folded line belongs to the header above it
            if not drop:
                out.append(line)
            continue
        drop = bool(ASKS.match(line))
        if not drop:
            out.append(line)
    new = b''.join(out)
    if new == head:
        return 1
    if new.endswith((b'\r\n', b'\n')) and raw[head_end:head_end + 1] in (b'\r', b'\n'):
        new = new.rstrip(b'\r\n')         # the empty line after the headers comes with the rest
    sys.stdout.buffer.write(new + raw[head_end:])
    sys.stdout.buffer.flush()
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as e:
        print('wombat-email-receipts: %s: %s' % (type(e).__name__, e), file=sys.stderr)
        sys.exit(2)
