#!/usr/bin/python

# mailheader_really_delivered_to.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--
#       October 31, 2006        bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       November 29, 2011       bar     pyflake cleanup
#       --eodstamps--
##      \file
#
#
#       Put a X-really-delivered-to: header on email that has been tagged with
#       a "X-From-IPadr:" header.
#
#


import  re

import  tzemail



OUR_HEADER      =   "X-really-delivered-to: "
IP_ADR_HEADER   =   "X-From-IPadr: "


delivered_to_re =   re.compile(r".*\nDelivered-to:\s+([^\n]+)\n.*?\n" + IP_ADR_HEADER, re.IGNORECASE + re.DOTALL)


def delivered_to_before_this(email, s) :
    """
        Given an email in array form with lines without EOLs,
        return the contents of the Delivered-to: header closest
        preceding any header containing the given string.
        If not found, return None.
    """

    email   = tzemail.get_flattened_email_headers_array(email)

    email   = "\n".join(email)
    g       = delivered_to_re.match(email)
    if  g   :
        return(g.group(1))

    return(None)




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

    hdrs    = tzemail.find_email_headers(email, IP_ADR_HEADER)
    if  len(hdrs) == 1 :
        ip  = hdrs[0]
        dto = delivered_to_before_this(email, ip)
        if  dto :
            tzemail.eliminate_email_header(email, OUR_HEADER)
            tzemail.add_email_header(      email, OUR_HEADER + dto)
        pass

    return(email)


#
#
#
if __name__ == '__main__' :

    import  sys

    import  TZCommandLineAtFile


    del sys.argv[0]

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    if  len(sys.argv) > 2 :
        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   = find_and_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

