#! /usr/bin/env python
#
# Copyright (C) 1998 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.

"Invoked by cron, checks for pending list requests and mails the admin if any."

import sys, os
import paths
from Mailman import MailList
from Mailman import mm_cfg
from Mailman import Utils

# Work around known problems with some RedHat cron daemons
import signal
signal.signal(signal.SIGCHLD, signal.SIG_DFL)

def main(verbose=0):

    for name in Utils.list_names():
	list = MailList.MailList(name, lock = 0)
        count = list.NumRequestsPending()
        if verbose:
            print name, count, list.GetAdminEmail()
	if count:
            text = Utils.maketext('checkdbs.txt',
                                  {'count': count,
                                   'host_name': list.host_name,
                                   'adminDB':
                                   list.GetAbsoluteScriptURL('admindb'),
                                   'real_name': list.real_name,
                                   })
	    list.SendTextToUser(subject = '%d %s admin request(s) waiting' % 
				(count, list.real_name),
				recipient = list.GetAdminEmail(),
				text = text + "\n" + pending_requests(list),
                                add_headers = ["Precedence: bulk"])

def pending_requests(list):
    import time, string
    pending = []
    requests = list.requests
    # First the pending subscriptions:
    if requests.has_key('add_member'):
	pending.append("Pending subscriptions:")
	for req in requests['add_member']:
	    id, when, digested, who, pwd = req
	    pending.append("\t%s %s" %
			   (string.strip(who),
			    time.ctime(when)))
    if requests.has_key('post'):
	if pending:
	    pending.append("")
	pending.append("Pending posts:")
	for req in requests['post']:
	    id, when, (who, msg), cause, subj = req
	    pending.append("\tFrom: %s on %s:\n\tCause: %s"
                           % (string.strip(who),
                              time.ctime(when),
                              `string.strip(cause)`))
    return string.join(pending, '\n')

if __name__ == "__main__":
    main(verbose=(len(sys.argv) > 1
                  and sys.argv[1] in ["-v", "--verbose"]))
