#!/usr/bin/env python

"""Remove old, unconfirmed messages from the pending queue.

Usage:  %(program)s [-c <file>] [-d] [-v] [-h] timeout

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

    -d
    --dry-run
       Don't actually remove files, just show what would have happened.
       This implies --verbose.
       
    -v
    --verbose
       Print a verbose display instead of the default silent display.

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

    timeout is the required minimum retention time in seconds (s),
    minutes (m), hours (h), days (d), weeks (w), months (M), or years
    (Y) for unconfirmed messages.  Messages older than timeout will be
    purged.

    e.g, %(program)s 30d
"""

import getopt
import glob
import os
import sys
import string
import time


program = sys.argv[0]
dry = None
verbose = None

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

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'c:dvh',
                               ['config-file=','dry-run','verbose','help'])
except getopt.error, msg:
    usage(1, msg)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage(0)
    elif opt in ('-c', '--config-file'):
        os.environ['TMDARC'] = arg
    elif opt in ('-d', '--dry-run'):
        dry, verbose = 1,1
        verbose = 1
    elif opt in ('-v', '--verbose'):
        verbose = 1


try:
    import paths
except ImportError:
    pass
    
from TMDA import Defaults
from TMDA import Util


# timeout is required
try:
    timeout = args[0]
except IndexError:
    usage(0)

pendingdir = Defaults.DATADIR + 'pending'
timeout_in_secs = Util.seconds(timeout)
now = '%d' %time.time()
# Anything less than this is history.
min_time = int(now) - int(timeout_in_secs)


def main():

    os.chdir(pendingdir)
    for msg in glob.glob('*.*.msg'):
        msg_split = string.split(msg,'.')
        msg_time = int(msg_split[0])
        if msg_time < min_time:
            if verbose:
                message = msg + ' is more than ' + \
                          Util.format_timeout(timeout) + ' old, deleting!'
                if dry:
                    message = message + ' (not)'
                print message
            if not dry:
                os.unlink(msg)


if __name__ == '__main__':
    main()
