#!/usr/bin/python
#
# Copyright (C) 1998-2003 by the Free Software Foundation, Inc.
# Portions Copyright (C) 2005 by Florian Weimer <fw@deneb.enyo.de>
#
# 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.

"""Check if an address is subscribed to a mailing list

Usage: %(PROGRAM)s [options] listname address

Where:

   --print
   -p

       Print "yes" or "no", depending on the list membership.

    --help
    -h
        Print this help message and exit.

    listname is the name of the mailing list to use.
    address is the email address which is checked for membership.
"""

import sys

sys.path = ['/usr/lib/mailman'] + sys.path
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 email.Utils import formataddr

PROGRAM = sys.argv[0]

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 main():
    print_result = False
    
    # 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)
        elif opt in ('-p', '--print'):
            print_result = True
        else:
            # No more options left, push the last one back on the list
            args.insert(0, opt)
            break

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

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

    try:
        mlist = MailList.MailList(listname, lock=False)
    except Errors.MMListError, e:
        if print_result:
            print "fail"
            sys.exit(0)
        else:
            print >> sys.stderr, _('No such list: %(listname)s')
            sys.exit(2)

    if print_result:
        if mlist.isMember(address):
            print "yes"
        else:
            print "no"
        sys.exit(0)
    else:
        if mlist.isMember(address):
            sys.exit(0)
        else:
            sys.exit(1)


if __name__ == '__main__':
    main()
