#!/usr/bin/python

# mailheader_unknown_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 3, 2006        bar     get the x-really-delivered-to header from its source
#       January 22, 2007        bar     ouch, i tested something and left the edit
#       May 28, 2007            bar     comment
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       --eodstamps--
##      \file
#
#
#       Put a X-unknown-delivered-to: header on email that has been tagged with
#       a "X-really-delivered-to:" header with a name than is not known to the given
#       IIstore.
#
#       This script is run for emails by procmail.
#       It's job is to identify emails that have been delivered to names that an IIstore knows to be bogus.
#
#       This script can read the input email from stdin or from a file, if given,
#       and can write output to stdout or to a file if given.
#
#


import  tzemail
import  IIstoreClient
import  mailheader_really_delivered_to



OUR_HEADER      =   "X-unknown-delivered-to: "


def apply_header(email, unknown_replies = None, host = None, port = None, user_name = None, password = None, iiname = None, precedent_str = "", timeout = None) :
    """
        Given an email in array form with lines without EOLs,
        apply the OUR_HEADER to the email if it can be.
    """

    unknown_replies = unknown_replies or [ 'unk' ]
    unknown_replies = tzlib.make_dictionary(map(lambda r : r.lower(), unknown_replies))

    tzemail.eliminate_email_header(email, OUR_HEADER)

    hdrs    = tzemail.find_email_headers(email, mailheader_really_delivered_to.OUR_HEADER)
    if  len(hdrs) == 1 :
        name    = hdrs[0]

        clt     = IIstoreClient.an_iistore_client(host, port, user_name, password, iiname, precedent_str, timeout)
        if  clt :

            # clt.screen_info = True

            r   = clt.make_query(name)
            if  r and unknown_replies.has_key(r.lower()) :
                tzemail.add_email_header(email, OUR_HEADER + name + " " + r)
            pass
        pass

    return(email)


#
#
#
if __name__ == '__main__' :

    import  sys

    import  tzlib
    import  TZCommandLineAtFile


    del sys.argv[0]

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    unknown_replies = []
    host            = None
    port            = None
    user_name       = None
    password        = None
    iiname          = None
    precedent_str   = None
    timeout         = 5.0


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--host", "-h" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        host        = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--port", "-p" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        port        = int(sys.argv.pop(oi))

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--user", "-u" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        user_name   = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--password", "-a" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        password    = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--iiname", "-i" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        iiname      = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--prec_str", "-s" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        precedent_str   = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--timeout", "-t" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        timeout         = float(sys.argv.pop(oi))

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--unknown", "-u" ])
        if  oi < 0 :    break
        del sys.argv[oi]
        unknown_replies.append(sys.argv.pop(oi))




    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, unknown_replies, host, port, user_name, password, iiname, precedent_str, timeout)

    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

