#!/usr/bin/python3

import re
import subprocess
import sys
import pathlib


def set_up():
    proc = subprocess.run(['tests/install.debian.sh'])
    proc.check_returncode()


def clean():
    subprocess.run("systemctl stop postfix-mta-sts-resolver")
    for db_ in pathlib.Path('/var/lib/mta/sts').glob('*'):
        db_.unlink()
    subprocess.run("systemctl start postfix-mta-sts-resolver")


def err(name, expected, got):
    msg = "failed {}: want <{}>, got <{}>".format(name, expected, got)
    print(msg, file=sys.stderr)


def test_daemon(name, domain, desired, policy):
    cmd = 'postmap -q ' + domain + ' socketmap:inet:127.0.0.1:8461:postfix'
    proc = subprocess.run(cmd.split(), capture_output=True, text=True)
    stdout = proc.stdout.strip()
    if desired and not stdout == policy:
        err('daemon ' + name, policy, stdout)
    if not desired and stdout != '':
        err('daemon ' + name, '', stdout)


def test_query(name, domain, desired, mx_):
    cmd = 'mta-sts-query ' + domain
    proc = subprocess.run(cmd.split(), capture_output=True, text=True)
    stdout = proc.stdout.strip()
    expected_output = "(<STSFetchResult.VALID: 1>, ('20180907T090909', {'mx': ['" + str(mx_) + "'], 'version': 'STSv1', 'mode': 'enforce', 'max_age': 86400}))"
    if desired and stdout != expected_output:
        err('query ' + name, expected_output, stdout)
    if not desired and 'VALID' in stdout and 'enforce' in stdout:
        err('query ' + name, '', stdout)


def main():
    regex = re.compile(r"""
        (?P<name>\S+\s
            (?P<domain>\S+)
        )
        \t
        (?P<status>\S+)
        (\s                    # optional
            (?P<policy>.+      # capture entire policy
                match=
                (?P<mx>\S+)    # capture only mx as well
                .*
            )
        )?
    """, re.VERBOSE)
    set_up()
    with pathlib.Path('tests/refdata.tsv').open() as tsv:
        for line in tsv:
            match = regex.fullmatch(line.strip())
            name, domain, desired = match.group(1, 2, 3)
            desired = True if desired == "OK" else False
            test_daemon(name, domain, desired, match.group('policy'))
            # skip syntax currently not supported by the query tool
            if not '[' in domain and not ':' in domain:
                test_query(name, domain, desired, match.group('mx'))


if __name__ == '__main__':
    main()
