#!/usr/local/bin/python

"""
modMail.py ...
  Takes mail in from stdin and modifies certain fields

"""

import os, sys, string, time, getopt
import re,marshal


def usage(progname):
  print "usage: %s" % progname
  print __doc__

def main(argv, stdout, environ):
  newTo   = None
  newFrom = None

  optlist, args = getopt.getopt(argv[1:], '', ['to=', 'from='])

  
  for (opt, val) in optlist:
    if opt == '--to':
      newTo = val
    if opt == '--from':
      newFrom = val


  if newTo == None or newFrom == None:
    print " Must specify --to and --from command line params"

  inFile  = sys.__stdin__
  errFile  = sys.__stderr__
  #print argv
  #print optlist
  z = inFile.read()

  #errFile.write('to = [%s]  from = [%s]' % (newTo, newFrom))

  ## Record Which List we received
  #t = time.time()

  if newTo != None:
    r = re.compile("^To: .*", re.M)
    z = re.sub(r, 'To: ' + newTo, z)

  if newFrom != None:
    r = re.compile("^From: .*", re.M)
    z = re.sub(r, 'From: ' + newFrom, z)

  #r = re.compile("^Subject: (.*)", re.M)
  #m = r.search(z)
  #subject = m.group(1)

  #r = re.compile("^From: (.*)", re.M)
  #m = r.search(z)
  #fromAddr = m.group(1)

  #r = re.compile("^Date: (.*)", re.M)
  #m = r.search(z)
  #emailDate = m.group(1)

  outFile = os.popen("/usr/sbin/sendmail -f%s %s" %(newFrom, newTo), "w" )
  outFile.write(z)
  outFile.close()
  


if __name__ == "__main__":
  main(sys.argv, sys.stdout, os.environ)



