#! /usr/bin/python
#
# Copyright (C) 1998-2003 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""Moves or Copies all the members of a mailing list to a new MemberAdaptor.

Usage: %(PROGRAM)s [options] listname

Where:

    -h
        Print this help message and exit.

    listname is the name of the mailing list to use.

"""

import sys
from types import UnicodeType

import paths
import email.Utils
from Mailman import mm_cfg
from Mailman import Utils
from Mailman import MailList
from Mailman import Errors
from Mailman import MemberAdaptor
from Mailman.i18n import _
from Mailman.UserDesc import UserDesc

from email.Utils import formataddr

### both MemberAdaptors need to be imported here
from Mailman.MysqlMemberships import MysqlMemberships
from Mailman.OldStyleMemberships import OldStyleMemberships


PROGRAM = sys.argv[0]
ENC = sys.getdefaultencoding()
COMMASPACE = ', '

try:
    True, False
except NameError:
    True = 1
    False = 0


WHYCHOICES = {'enabled' : MemberAdaptor.ENABLED,
              'unknown' : MemberAdaptor.UNKNOWN,
              'byuser'  : MemberAdaptor.BYUSER,
              'byadmin' : MemberAdaptor.BYADMIN,
              'bybounce': MemberAdaptor.BYBOUNCE,
              }


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



def safe(s):
    if not s:
        return ''
    if isinstance(s, UnicodeType):
        return s.encode(ENC, 'replace')
    return unicode(s, ENC, 'replace').encode(ENC, 'replace')


def isinvalid(addr):
    try:
        Utils.ValidateEmail(addr)
        return False
    except Errors.EmailAddressError:
        return True

def isunicode(addr):
    return isinstance(addr, UnicodeType)



def whymatches(mlist, addr, why):
    # Return true if the `why' matches the reason the address is enabled, or
    # in the case of why is None, that they are disabled for any reason
    # (i.e. not enabled).
    status = mlist.getDeliveryStatus(addr)
    if why is None:
        return status <> MemberAdaptor.ENABLED
    return status == WHYCHOICES[why]



def main():
    # Throw away the first (program) argument
    args = sys.argv[1:]
    if not args:
        usage(0)

    while True:
        try:
            opt = args.pop(0)
        except IndexError:
            usage(1)
        if opt in ('-h', '--help'):
            usage(0)
        else:
            # No more options left, push the last one back on the list
            args.insert(0, opt)
            break

    if len(args) <> 1:
        usage(1)

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

    try:
        source = MailList.MailList(listname, lock=False)
    except Errors.MMListError, e:
        print >> sys.stderr, _('No such list: %(listname)s')
        sys.exit(1)


    dest = MailList.MailList(listname, lock=True)

    # choose a different MemberAdaptor for source and dest :-)
    source._memberadaptor = OldStyleMemberships(source)
    dest._memberadaptor = MysqlMemberships(dest)

    # below is the code for the reverse operation (from MySQL to OldStyle) - uncomment
    #dest._memberadaptor = OldStyleMemberships(dest)
    #source._memberadaptor = MysqlMemberships(source)

    # Get the lowercased member addresses
    members = source.getMembers()

    for addr in members:
        # Insert subscriber in the list
        # with name, password, digest & language
        name = safe(source.getMemberName(addr) or '')
        userdesc = UserDesc(addr,
            name,
            source.getMemberPassword(addr) or '',
            source.getMemberOption(addr,mm_cfg.Digests),
            source.getMemberLanguage(addr) or ''
        )
        print "%s, %s" % (addr, name)
        try:
            dest.ApprovedAddMember(userdesc, False, False)
            # copy the flags
            for flag in (2,4,8,16,32,64,128,256):
                dest.setMemberOption(addr, flag, source.getMemberOption(addr, flag))
            # copy the delivery status
            dest.setDeliveryStatus(addr, source.getDeliveryStatus(addr))
            print 'Added to destination : %s' %(formataddr((safe(name), addr)))
        except Errors.MMAlreadyAMember:
            print 'Already in destination : %s' %(formataddr((safe(name), addr)))
        
    # Save() the results
    dest.Save()
    dest.Unlock()

    # you can delete them from the older MemberAdaptor
    # using bin/remove_members --all --nouserack --noadminack listname

if __name__ == '__main__':
    main()
