# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
import getopt
import sys


def usage(exit_code):
    print(
        """
The utility returns settings of mailman mailing lists in the Python representation format.

Usage: python mailman_backup.py <options>
Options:
  --mailman-lib=<path>    Path to mailman Python library.
  --lists-from=<path>     New line separated list of mailing lists names (without a domain part).
  --help
""".strip()
    )
    sys.exit(exit_code)


def main():
    options = []
    try:
        options, _ = getopt.getopt(sys.argv[1:], '', ['mailman-lib=', 'lists-from=', 'help'])
    except Exception as e:
        print(str(e))
        usage(1)

    mailman_lib_path = lists_from_path = None
    for option, arg in options:
        if option == '--help':
            usage(0)
        elif option == '--mailman-lib':
            mailman_lib_path = arg
        elif option == '--lists-from':
            lists_from_path = arg
        else:
            usage(1)

    if not mailman_lib_path or not lists_from_path:
        usage(1)

    sys.path.append(mailman_lib_path)

    lists_file = open(lists_from_path, 'rb')
    lists_names = []
    try:
        lists_names = lists_file.read().splitlines()
    finally:
        lists_file.close()

    from Mailman.MailList import MailList
    result = {}
    for list_name in lists_names:
        mail_list = None
        try:
            mail_list = MailList(list_name.lower(), lock=0)
        except Exception as e:
            result[list_name] = {
                'error': "Failed to get maillist '%s': %s" % (list_name, str(e))
            }
            continue
        members_keys = mail_list.getRegularMemberKeys()
        result[list_name] = {
            'password': mail_list.password,
            'password_type': 'hash',
            'owners': mail_list.owner,
            'subscribers': mail_list.getMemberCPAddresses(members_keys),
        }
    print(repr(result))


if __name__ == '__main__':
    main()
