#!/usr/bin/env python

#################################################################
# This is a wrapper around the real filter (tmda-rfilter) script.
#
# It catches all possible exceptions and exits EX_TEMPFAIL to
# defer the delivery if anything but SystemExit is thrown.
#
# The traceback is also written to the user's LOGFILE_DEBUG if
# possible, and if not ~/TMDA_DELIVERY_FAILURE, and if not again,
# to stdout.
#################################################################

import sys
tb1 = tb2 = tb3 = None
status = 0
fp = sys.stdout

try:
    import os
    import sys
    import traceback
    
    try:
        import paths
    except ImportError:
        pass

    from TMDA import Errors
    
    program = sys.argv[0]
    execdir = os.path.dirname(os.path.abspath(program))
    execfile(os.path.join(execdir, 'tmda-rfilter'))
    
except KeyboardInterrupt:
    pass

except (StandardError, Errors.TMDAError):
    try:
        status = 75
        tb1 = sys.exc_info()
        import string, time

        from TMDA.Defaults import LOGFILE_DEBUG
        if not LOGFILE_DEBUG:
            raise NameError, 'LOGFILE_DEBUG is not defined'
        print 'Exception', LOGFILE_DEBUG
        fp = open(LOGFILE_DEBUG, 'a')

    except (StandardError, Errors.TMDAError):
        try:
            print 'Exception', '~/TMDA_DELIVERY_FAILURE'
            tb2 = sys.exc_info()
            fp = open(os.path.expanduser('~/TMDA_DELIVERY_FAILURE'), 'a')
        except (StandardError, Errors.TMDAError):
            tb3 = sys.exc_info()

if status:
    try:
        log_header = ('%s (%s):%s' %
                      ('\n' + 'Uncaught Python '
                       + string.split(sys.version)[0] + ' exception',
                       time.asctime(time.gmtime(time.time())) + ' UTC',
                       '\n' + '-' * 60 + '\n'))
        fp.write(log_header)
        for tb in (tb1, tb2, tb3):
            if tb:
                traceback.print_exception(tb[0], tb[1],
                                          tb[2], file=fp)
        fp.close()

    except:
        pass

sys.exit(status)
