#!/usr/bin/python

# bounce_originator.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       November 1, 2006        bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.bounce_originator
#
#
#       Put a X-Bounce-Originating-IPadr: header on email.
#
#       This header is put on as best we can guess it.
#       The header tells what we guess to be the originating IP address of the email that caused the bounce.
#
#

import  re

import  tzemail



OUR_HEADER                      =   "X-Bounce-Originating-IPadr: "

find_bounce_originating_ip_re   =   re.compile(r"The\s+original\s+message\s+was\s+received\s+at\s+[^\[\(]+?\s+from\s+\S+\s+[\[\(](\d+\.\d+\.\d+\.\d+)[\]\)]", re.IGNORECASE + re.DOTALL)

def apply_header(email) :
    """
        Given an email in array form with lines without EOLs,
        apply the OUR_HEADER to the email if it can be.
    """

    tzemail.eliminate_email_header(email, OUR_HEADER)

    body    = tzemail.get_email_body_string(email)

    g       = find_bounce_originating_ip_re.search(body)
    if  g :
        tzemail.add_email_header(email, OUR_HEADER + g.group(1))

    return(email)


#
#
#
if __name__ == '__main__' :

    import  sys


    del sys.argv[0]

    if  len(sys.argv) > 2 :
        print sys.argv
        raise("Just tell me an input and output file. Nothing more.")


    if  len(sys.argv) > 0 :
        fi  = open(sys.argv.pop(0), "r")
    else :
        fi  = sys.stdin

    email   = tzemail.read_email_from_file(fi)

    if  fi != sys.stdin :
        fi.close()

    email   = apply_header(email)

    if  len(sys.argv) > 0 :
        fo  = open(sys.argv.pop(0), "w")
    else :
        fo  = sys.stdout

    #
    #   Write the email out to stdout
    #
    for li in email :
        print >> fo, li

    if  fo != sys.stdout :
        fo.close()

    pass

#
#
#
# eof
