#!/usr/bin/python3 -I
# Wombat-Email: mailboxes' public keys, from the database to where they're used
# (installer/65-private.sh runs it as root on every run and after a change in the panel):
#   /var/lib/wombat-email/pgp-keys/ADDRESS.pgp      a private mailbox's key, only its User ID for ADDRESS
#                                                   (delivery reads it; webmail's notice checks for it)
#   /etc/postfix/wombat-email/private-transport     which addresses go through wombat-pgp (then postmap)
#   /var/www/wombat-email/discovery/DOMAIN/openpgpkey/.well-known/openpgpkey/DOMAIN/hu/HASH
#                                                   every key, private or only published, in the domain's
#                                                   Web Key Directory, where mail apps look it up
#                                                   (served at openpgpkey.DOMAIN, 85-web)
#   /var/lib/wombat-email/pgp-keys.json            each key's end date and problem, for the panel and the
#                                                   daily report (which runs this every morning, so a key
#                                                   that ended leaves the key directory the same day)
# Prints one line per change ("changed: ..."), and "problem: ..." for a key that can't be used.
# Exit 0; the caller reloads Postfix when the transport map changed ("transport" on the last line).
import glob, hashlib, json, os, subprocess, sys, tempfile, time

sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

KEYS = '/var/lib/wombat-email/pgp-keys'
MAP = '/etc/postfix/wombat-email/private-transport'
STATUS = '/var/lib/wombat-email/pgp-keys.json'
WKD = '/var/www/wombat-email/discovery/%s/openpgpkey/.well-known/openpgpkey/%s/hu'


def wkd_hash(local):
    """The Web Key Directory's name for a local part: SHA-1 of it in lower case (ASCII only), z-base-32."""
    digest = hashlib.sha1(local.encode().translate(bytes.maketrans(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ', b'abcdefghijklmnopqrstuvwxyz'))).digest()
    alphabet, n, out = 'ybndrfg8ejkmcpqxot1uwisza345h769', int.from_bytes(digest, 'big'), ''
    for i in range(32):
        out = alphabet[n & 31] + out
        n >>= 5
    return out


def db_rows():
    rows = we.psql("SELECT m.email, m.pgp_encrypt, encode(convert_to(m.pgp_key, 'UTF8'), 'hex') FROM mailboxes m "
                   "WHERE m.pgp_key IS NOT NULL AND NOT m.relay ORDER BY m.email", rows=True)
    return [(e, enc == 't', bytes.fromhex(h)) for e, enc, h in (r for r in rows if len(r) == 3)]


def gpg(home, *args, data=None):
    return subprocess.run(['/usr/bin/gpg', '--batch', '--no-tty', '--quiet', '--homedir', home, *args],
                          input=data, capture_output=True, timeout=60)


def ends(cols):
    """When the key stops being usable for encryption (seconds), or None for never: the main key's end
    date, or the last end date of its parts that can encrypt, whichever comes first."""
    pub = next((c.split(':') for c in cols if c.startswith('pub:')), None)
    if pub is None:
        return None
    end = int(pub[6]) if pub[6].isdigit() else None
    subs = [c.split(':') for c in cols if c.startswith('sub:')]
    enc = [f for f in subs if 'e' in f[11] and f[1] not in ('r', 'd', 'i')] + ([pub] if 'e' in pub[11] else [])
    if enc:
        if any(not f[6].isdigit() for f in enc):
            last = None
        else:
            last = max(int(f[6]) for f in enc)
        if last is not None:
            end = last if end is None else min(end, last)
    return end


def key_for(addr, armored):
    """The key with only ADDRESS's User ID (binary), or (None, why); and when it ends (or None)."""
    with tempfile.TemporaryDirectory(prefix='wombat-pgp-') as home:
        os.chmod(home, 0o700)
        if gpg(home, '--import', data=armored).returncode != 0:
            return None, "isn't an OpenPGP public key", None
        cols = gpg(home, '--with-colons', '--list-keys').stdout.decode(errors='replace').splitlines()
        pubs = [c for c in cols if c.startswith('pub:')]
        if len(pubs) != 1:
            return None, 'holds %d keys, not one' % len(pubs), None
        end = ends(cols)
        f = pubs[0].split(':')
        if f[1] in ('r', 'e', 'd', 'i'):
            return None, {'r': 'is revoked', 'e': 'has expired', 'd': 'is disabled', 'i': 'is invalid'}[f[1]], end
        if 'E' not in f[11]:
            return None, 'has no key that can encrypt (or it has expired)', end
        uids = [c.split(':')[9] for c in cols if c.startswith('uid:') and c.split(':')[1] not in ('r', 'e')]
        a = addr.lower()
        if not any('<%s>' % a in u.lower() or u.lower() == a for u in uids):
            return None, 'has no User ID for %s' % addr, end
        r = gpg(home, '--export', '--export-options', 'export-minimal', '--export-filter', 'keep-uid=mbox = %s' % addr.lower())
        if r.returncode != 0 or not r.stdout:
            return None, "couldn't be exported", end
        return r.stdout, '', end


def main():
    os.makedirs(KEYS, mode=0o755, exist_ok=True)
    want, published = {}, {}   # private mailboxes (mail encrypted), and keys only published
    status = {}
    for addr, encrypt, armored in db_rows():
        key, why, end = key_for(addr, armored)
        status[addr] = {'private': encrypt, 'ends': end, 'problem': why}
        if key is None and encrypt:
            print('problem: the public key for %s %s: its mail waits in the queue until it has a usable key' % (addr, why))
            # its mail still goes through wombat-pgp, which keeps it waiting: never stored unencrypted
            want[addr] = None
        elif key is None:
            print('problem: the public key for %s %s: it is not published' % (addr, why))
        elif encrypt:
            want[addr] = key
        else:
            published[addr] = key
    changed_map = False
    for addr, key in want.items():
        path = os.path.join(KEYS, addr + '.pgp')
        if key is None:
            continue
        old = open(path, 'rb').read() if os.path.exists(path) else None
        if old != key:
            tmp = path + '.new'
            with open(tmp, 'wb') as fh:
                fh.write(key)
            os.chmod(tmp, 0o644)
            os.replace(tmp, path)
            print('changed: %s (public key of %s)' % (path, addr))
    for name in sorted(os.listdir(KEYS)):
        if name.endswith('.pgp') and name[:-4] not in want:
            os.remove(os.path.join(KEYS, name))
            print('changed: %s removed (%s is no longer private)' % (os.path.join(KEYS, name), name[:-4]))
        elif name.endswith('.pgp') and want.get(name[:-4]) is None:
            os.remove(os.path.join(KEYS, name))   # an unusable key: its mail waits
            print('changed: %s removed (its key is no longer usable)' % os.path.join(KEYS, name))
    # the Web Key Directory: one file per usable key, the rest removed
    wkd = {}
    for addr, key in list(want.items()) + list(published.items()):
        if key is not None:
            local, _, dom = addr.rpartition('@')
            wkd[os.path.join(WKD % (dom, dom), wkd_hash(local))] = (addr, key)
    for path, (addr, key) in sorted(wkd.items()):
        old = open(path, 'rb').read() if os.path.exists(path) else None
        if old != key:
            os.makedirs(os.path.dirname(path), mode=0o755, exist_ok=True)
            with open(path + '.new', 'wb') as fh:
                fh.write(key)
            os.chmod(path + '.new', 0o644)
            os.replace(path + '.new', path)
            print('changed: %s (%s in the Web Key Directory)' % (path, addr))
    for path in glob.glob(WKD % ('*', '*') + '/*'):
        if path not in wkd:
            os.remove(path)
            print('changed: %s removed from the Web Key Directory' % path)
    text = '# Wombat-Email: private mailboxes, delivered through wombat-pgp (installer/65-private.sh, made by\n' \
           '# wombat-email-pgp-keys from the database; change them in the panel).\n' \
           + ''.join('%s wombat-pgp:\n' % a for a in sorted(want))
    old = open(MAP).read() if os.path.exists(MAP) else None
    if old != text or not os.path.exists(MAP + '.db'):
        tmp = MAP + '.new'
        with open(tmp, 'w') as fh:
            fh.write(text)
        os.chmod(tmp, 0o644)
        os.replace(tmp, MAP)
        subprocess.run(['/usr/sbin/postmap', MAP], check=True)
        print('changed: %s (%d private mailbox%s)' % (MAP, len(want), '' if len(want) == 1 else 'es'))
        changed_map = True
    text = json.dumps({'checked': int(time.time()), 'keys': status}, indent=1, sort_keys=True)
    old = open(STATUS).read() if os.path.exists(STATUS) else ''
    if old.split('\n', 2)[2:] != text.split('\n', 2)[2:]:   # the time alone isn't a change worth writing
        with open(STATUS + '.new', 'w') as fh:
            fh.write(text)
        os.chmod(STATUS + '.new', 0o644)
        os.replace(STATUS + '.new', STATUS)
    if changed_map:
        print('transport')


if __name__ == '__main__':
    main()
