#!/usr/bin/env python
#
# Copyright (C) 2001,2002 Jason R. Mastaler <jason@mastaler.com>
#
# This file is part of TMDA.
#
# TMDA 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.  A copy of this license should
# be included in the file COPYING.
#
# TMDA 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 TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""Pending queue manipulation tool.

Usage:  %(program)s [OPTIONS] [messages ... | - ]

Where:
    -c <file>
    --config-file <file>
       Specify a different configuration file other than ~/.tmda/config.

    -i
    --interactive
       Display a summary of each pending message and prompt for
       disposal (pass, show, release, delete, quit).  Implies
       --verbose.  (default)

    -p
    --pretend
       Don't actually operate on messages, just show what would have happened.
       Implies --verbose.

    -b
    --batch
       Operate non-interactively.  Use with caution.
       
    -r
    --release
       Release messages.

    -d
    --delete
       Delete messages.

    -B
    --blacklist
       Append the sender of the message to the PENDING_BLACKLIST_APPEND file.

    -W
    --whitelist
       Append the sender of the message to the PENDING_WHITELIST_APPEND file.

    -s
    --summary
       Print a summary of pending messages along with a release address link.
       Implies --verbose.

    -T
    --terse-summary
       Print a terse (one-line per message) summary of pending messages.
       Customize display with TERSE_SUMMARY_HEADERS. Implies --verbose.
       
    -S
    --show
       Display the full contents of the given message with $PAGER (usually
       the `more', or `less' program).
       
    -C
    --cache
       Operate only on messages which aren't stored in .msgcache (i.e,
       haven't yet been seen).  After operation, store the message in
       .msgcache.  Useful primarily in conjunction with the --summary
       option.
       
    -A
    --ascending
       Operate on messages in ascending order (default).

    -D
    --descending
       Operate on messages in descending order.
      
    -R <user@host>
    --recipient <user@host>
       Override the address used to create the magic release address.
       Normally, this is determined by parsing the `X-TMDA-Recipient'
       header which every pending message should contain.

    -Y <interval>
    --younger <interval>
       Operate only on messages younger than the time interval given in
       seconds (s), minutes (m), hours (h), days (d), weeks (w), months
       (M), or years (Y).

    -O <interval>
    --older <interval>
       Operate only on messages older than the time interval given in
       seconds (s), minutes (m), hours (h), days (d), weeks (w), months
       (M), or years (Y).

    -v
    --verbose
       Display output (default).

    -q
    --quiet
       Suppress output.  Not compatible with --interactive.

    -V
    --version
       Print TMDA version information and exit.
 
    -h
    --help
       Print this help message and exit.

    messages | -
       If one or more messages are provided, operate just on them. 
       If `-' is specified, operate on a list of messages provided by
       standard input. Otherwise, operate on all messages in the pending queue.
       
    Examples:

    (interactively operate on all pending messages)
    %(program)s 

    (interactively operate on just these messages)
    %(program)s 1012182077.5803.msg 1012939546.7870.msg

    (immediately release these messages from the pending queue)
    %(program)s -b -r 1012182077.5803.msg 1012939546.7870.msg

    (immediately release any messages with `foobar' in them)
    %(program)s -b -T | grep foobar | awk '{print $1}' | %(program)s -b -r -

    (immediately delete all messages from the pending queue)
    %(program)s -b -d

    (silently and immediately delete all messages older than 30 days)
    %(program)s -q -b -d -O 30d
    
    (mail a summary report of all new pending messages)
    %(program)s -C -b -s | mail -s 'TMDA pending summary' jason
"""

import getopt
import os
import sys

try:
    import paths
except ImportError:
    # Prepend /usr/lib/python2.x/site-packages/TMDA/pythonlib
    sitedir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3],
                           'site-packages', 'TMDA', 'pythonlib')
    sys.path.insert(0, sitedir)

import email

from TMDA import Version


program = sys.argv[0]
# Defaults
cache = None
command_recipient = None
descending = None
dispose = None
interactive = 1
older = None
pretend = None
summary = None
terse = None
threshold = None
verbose = 1
younger = None


def usage(code, msg=''):
    print __doc__ % globals()
    if msg:
        print msg
    sys.exit(code)

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'c:ipbrdBWsTSCADR:Y:O:vqVh', ['config-file=',
                                                             'interactive',
                                                             'pretend',
                                                             'batch',
                                                             'release',
                                                             'delete',
                                                             'blacklist',
                                                             'whitelist',
                                                             'summary',
                                                             'terse-summary',
                                                             'show',
                                                             'cache',
                                                             'ascending',
                                                             'descending',
                                                             'recipient=',
                                                             'younger=',
                                                             'older=',
                                                             'verbose',
                                                             'quiet',
                                                             'version',
                                                             'help'])
except getopt.error, msg:
    usage(1, msg)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage(0)
    if opt == '-V':
        print Version.ALL
        sys.exit()
    if opt == '--version':
        print Version.TMDA
        sys.exit()
    elif opt in ('-c', '--config-file'):
        os.environ['TMDARC'] = arg
    elif opt in ('-i', '--interactive'):
        interactive = verbose = 1
    elif opt in ('-p', '--pretend'):
        pretend = verbose = 1
    elif opt in ('-b', '--batch'):
        interactive = 0
    elif opt in ('-r', '--release'):
        dispose = 'release'
    elif opt in ('-d', '--delete'):
        dispose = 'delete'
    elif opt in ('-B', '--blacklist'):
        dispose = 'blacklist'
    elif opt in ('-W', '--whitelist'):
        dispose = 'whitelist'
    elif opt in ('-s', '--summary'):
        summary = 1
    elif opt in ('-T', '--terse-summary'):
        terse = 1
    elif opt in ('-S', '--show'):
        dispose = 'show'
    elif opt in ('-C', '--cache'):
        cache = 1
    elif opt in ('-A', '--ascending'):
        descending = 0
    elif opt in ('-D', '--descending'):
        descending = 1
    elif opt in ('-R', '--recipient'):
        command_recipient = arg
    elif opt in ('-Y', '--younger'):
        younger = 1
        threshold = arg
    elif opt in ('-O', '--older'):
        older = 1
        threshold = arg
    elif opt in ('-q', '--quiet'):
        verbose = 0
    elif opt in ('-v', '--verbose'):
        verbose = 1


from TMDA import Pending
from TMDA import Errors

def cprint(verbose=1, *strings):
    """Conditionally print one or more strings."""
    if verbose:
        for s in strings:
            print s,
        print
    else:
        return

def main():

    if interactive:
        QueueObject = Pending.InteractiveQueue
    else:
        QueueObject = Pending.Queue
    try:
        q = QueueObject(
            msgs = args,
            cache = cache,
            command_recipient = command_recipient,
            descending = descending,
            dispose = dispose,
            older = older,
            summary = summary,
            terse = terse,
            threshold = threshold,
            verbose = verbose,
            younger = younger,
            pretend = pretend
            ).initQueue()
        q.mainLoop()
    except Errors.QueueError, obj:
        print obj
        sys.exit(1)

# This is the end my friend.
if __name__ == '__main__':
    main()
