#!/usr/bin/python3 -I
# Wombat-Email: asks wombat-email-images (installer/91-images.sh) to fetch a message's pictures now and
# show the kept copies. Message on stdin; the new message on stdout and exit 0, or nothing on stdout and
# exit 1 when it stays as it came (no pictures, spam, signed, switched off), 2 when asking failed (it
# stays as it came too).
#   wombat-email-images-ask MAILBOX
# Used by Dovecot's delivery filter (as vmail, with $USER) and by the private mailboxes' delivery
# (wombat-email-pgp-deliver, before it encrypts: the last moment the server sees the message).
import os, socket, sys

SOCK = '/run/wombat-email-images.sock'
MAX = 25 * 1024 * 1024


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 '\n' in box or len(raw) > MAX:
        return 1
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.settimeout(55)   # the service gives up on pictures after 40 s; Dovecot waits 60
    s.connect(SOCK)
    s.sendall(box.encode() + b'\n' + raw)
    s.shutdown(socket.SHUT_WR)
    buf = bytearray()
    while True:
        chunk = s.recv(1 << 20)
        if not chunk:
            break
        buf += chunk
    if buf == b'SAME\n':
        return 1
    if not buf.startswith(b'NEW\n') or len(buf) < 100:
        return 2
    sys.stdout.buffer.write(buf[4:])
    sys.stdout.buffer.flush()
    return 0


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