#!/usr/bin/python

"""Create a mailing list.

Usage: %(program)s [options] listname owner created_by

Where:

    --domain=DOMAIN

    -h / --help
        Print this text and exit.

"""

from __future__ import print_function;

import os
import sys
import getopt
import paths
import re
import time

from Mailman import mm_cfg
from Mailman import MailList
from Mailman import Utils
from Mailman import Errors
from Mailman.i18n import _

program = sys.argv[0]

def usage(code, msg=''):
    if code:
        fd = sys.stderr
    else:
        fd = sys.stdout
    print(_(__doc__), file=fd)
    if msg:
        print(msg, file=fd)
    sys.exit(code)



def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'h',
                                   ['domain=',
                                    'help'])
    except getopt.error, msg:
        usage(1, msg)

    domain = None
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('--domain'):
            domain = arg

    mlname, owner_mail, created_by = args

    listname = mlname.lower()
    host_name = mm_cfg.DEFAULT_EMAIL_HOST
    listpasswd = Utils.MakeRandomPassword(20)
    lang = mm_cfg.DEFAULT_SERVER_LANGUAGE
    urlhost = mm_cfg.DEFAULT_URL_HOST
    web_page_url = mm_cfg.DEFAULT_URL_PATTERN % urlhost

    if Utils.list_exists(listname):
        usage(1, _('List already exists: %(listname)s'))

    if not listpasswd:
        usage(1, _('The list password cannot be empty'))

    mlist = MailList.MailList()
    try:
        owner_mails = owner_mail.split(',')
        pw = Utils.sha_new(listpasswd).hexdigest()
        # Guarantee that all newly created files have the proper permission.
        # proper group ownership should be assured by the autoconf script
        # enforcing that all directories have the group sticky bit set
        oldmask = os.umask(002)
        try:
            try:
                if lang == mm_cfg.DEFAULT_SERVER_LANGUAGE:
                    langs = [lang]
                else:
                    langs = [lang, mm_cfg.DEFAULT_SERVER_LANGUAGE]
                mlist.Create(listname, owner_mails[0], pw, langs=langs,
                             emailhost=host_name, urlhost=urlhost)
            finally:
                os.umask(oldmask)
        except Errors.BadListNameError, s:
            usage(1, _('Illegal list name: %(s)s'))
        except Errors.EmailAddressError, s:
            usage(1, _('Bad owner email address: %(s)s') +
                     _(' - owner addresses need to be fully-qualified names'
                       ' like "owner@example.com", not just "owner".'))
        except Errors.MMListAlreadyExistsError:
            usage(1, _('List already exists: %(listname)s'))

        # Assign domain-specific attributes
        mlist.host_name = host_name
        mlist.web_page_url = web_page_url

        # And assign the preferred language
        mlist.preferred_language = lang

        mlist.real_name = mlname
        mlist.owner = owner_mails
        ## Non-standard attributes for TUFS
        mlist.created_by = created_by
        mlist.created_date = time.strftime("%Y/%m/%d %H:%M:%S")

        mlist.Save()
    finally:
        mlist.Unlock()

    # Now do the MTA-specific list creation tasks
    if mm_cfg.MTA:
        modname = 'Mailman.MTA.' + mm_cfg.MTA
        __import__(modname)
        sys.modules[modname].create(mlist)



if __name__ == '__main__':
    main()

