'''
closed/durusmail/lib/mailman.py
'''

# If you have a port install of mailman, add this sym-link:
# - cd /opt/local/libexec/mailman; ln -s /opt/local/share/mailman/bin bin

from subprocess import Popen, PIPE
import sys

def cmd(args, input=None):
    try:
        p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(input=input)
    except OSError:
        print('subprocess popen error executing command:')
        print(' '.join(args))
        print(sys.exc_info()[1])
    return p

def is_subscribed(user, list_name):
    if not user.get_email():
        return False
    args = ['/www/mailman/bin/find_member', '-l', list_name, user.get_email()]
    stdout_output, stderr_output = cmd(args)
    if stderr_output:
        print('mailman.is_subscribed error: %s' % stderr_output)
        return None
    print stdout_output
    return list_name in stdout_output

def subscribe(user, list_name):
    if not user.get_email():
        return False, '%s has no email address' % user.get_id()
    if is_subscribed(user, list_name):
        return False, '%s is already a member of %s' % (user.get_email(), list_name)
    email = user.get_email()
    if user.format_realname():
        email = '"%s" <%s>' % (user.format_realname(), email)
    args = ['/www/mailman/bin/add_members', '-r', '-', list_name]
    stdout_output, stderr_output = cmd(args, input=email)
    if stderr_output:
        return False, stderr_output

    return True, '%s now subscribed to %s' % (user.get_email(), list_name)

def un_subscribe(user, list_name):
    if not user.get_email():
        return False, '%s has no email address' % user.get_id()
    if not is_subscribed(user, list_name):
        return False, '%s is not a member of %s' % (user.get_email(), list_name)
    args = ['/www/mailman/bin/remove_members', '-f', '-', list_name]
    stdout_output, stderr_output = cmd(args, input=user.get_email())
    if stderr_output:
        return False, stderr_output

    return True, '%s Unsubscribed from %s' % (user.get_email(), list_name)

def list_lists():
    args = ['/www/mailman/bin/list_lists', '-a']
    stdout_output, stderr_output = cmd(args)
    if stderr_output:
        print('mailman.list_lists error: %s' % stderr_output)
        return None
    lists = []
    for line in stdout_output.split('\n'):
        if ' - ' in line:
            list_realname, list_description = line.split(' - ', 1)
            lists.append((list_realname.strip(), list_description))
    return lists

def get_list_realname_and_description(list_name):
    for list_realname, list_description in list_lists() or []:
        if list_realname.lower() == list_name:
            return list_realname, list_description
