#!/usr/bin/python

"""Delete a mailing list.

Usage: %(program)s [options] listname

Where:

    --archives

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

"""

from __future__ import print_function;

import os
import sys
import getopt
import paths
import re
import shutil

from Mailman import mm_cfg
from Mailman import MailList
from Mailman import Utils
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 remove_it(listname, filename, msg):
    if os.path.islink(filename):
        os.unlink(filename)
    elif os.path.isdir(filename):
        shutil.rmtree(filename)
    elif os.path.isfile(filename):
        os.unlink(filename)


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

    archives = False
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('--archives'):
            archives = True

    mlname = args[0]
    listname = mlname.lower()

    if not Utils.list_exists(listname):
        usage(1, _('No such list (or list already deleted): %(listname)s'))

    REMOVABLES = []

    if Utils.list_exists(listname):
        mlist = MailList.MailList(listname, lock=0)
        REMOVABLES = [
            (os.path.join(mm_cfg.LIST_DATA_DIR, listname), _('list info')),
            ]
    else:
        mlist = None

    # Remove any stale locks associated with the list
    for filename in os.listdir(mm_cfg.LOCK_DIR):
        fn_listname = filename.split('.')[0]
        if fn_listname == listname:
            REMOVABLES.append((os.path.join(mm_cfg.LOCK_DIR, filename),
                               _('stale lock file')))

    # Remove any held messages for this list
    for filename in os.listdir(mm_cfg.DATA_DIR):
        cre = re.compile('^heldmsg-%s-\d+\.(pck|txt)$' % listname,
                         re.IGNORECASE)
        if cre.match(filename):
            REMOVABLES.append((os.path.join(mm_cfg.DATA_DIR, filename),
                               _('held message file')))

    if archives:
        REMOVABLES.extend([
            (os.path.join(mm_cfg.PRIVATE_ARCHIVE_FILE_DIR, listname),
             _('private archives')),
            (os.path.join(mm_cfg.PRIVATE_ARCHIVE_FILE_DIR, listname + '.mbox'),
             _('private archives')),
            (os.path.join(mm_cfg.PUBLIC_ARCHIVE_FILE_DIR, listname),
             _('public archives')),
            (os.path.join(mm_cfg.PUBLIC_ARCHIVE_FILE_DIR, listname + '.mbox'),
             _('public archives')),
            ])

    for dir, msg in REMOVABLES:
        remove_it(listname, dir, msg)

    if mlist:
        # Do the MTA-specific list deletion tasks
        if mm_cfg.MTA:
            modname = 'Mailman.MTA.' + mm_cfg.MTA
            __import__(modname)
            sys.modules[modname].remove(mlist)



if __name__ == '__main__':
    main()

