#!/usr/bin/env python

# herbrip_pin = Herbrip procmail-format incoming message handler
#
###############################################################
# Copyright (c) 2002 Philip Hunt.
# You are permitted to use this software under the terms of the 
# GNU General Public License. Details are in the file COPYING, 
# which you should have received with this distribution.
###############################################################

# Last altered: 28-Jan-2002
# History:
# 22-Jan-2002 PH: created

"""***
Usage:

   herbrip_pin <message_incoming >incoming_processed

herbrip_pin is desined to be invoked by Procmail. Its purpose
is to capture all incoming mail before the MUA gets it. The 
incoming mail is then processed. This program doesn't itself do 
the processing; it merely passes it on to the <herbrip> 
executable, which does.

The functionality and design of herbrip_pin are based on <herbin>
script written by Brian Salter-Duke <b_duke@lacebark.ntu.edu.au>.
***"""

#***** python standard libraries:
import sys
import os
import os.path
import getopt

#***** herbrip modules:
import startup


debug = 0 # debugging this module?
debugOutputFn = "~/.herbivore/pin_log"

# directory where the herbrip program is:
# (There's probably a better way to do this)
###herbripDir = "/home/philh/proj/herbrip/src/"
fullPathToMe = os.path.abspath(sys.argv[0])
herbripDir = os.path.dirname(fullPathToMe)

#---------------------------------------------------------------------

def cmdLineQuote(str):
   """ return a string, quoted appropriately for the command line """
   return "'%s'" % str


def main():
   # --dir, --dest options as with herbrip:

   dirValue = None
   dirCmdLine = ""
   destValue = None
   destCmdLine = ""
   try:
      opts,args = getopt.getopt(sys.argv[1:], "",
         ["dir=", "dest="])
   except:
      # print help info, and exit
      #usage()
      sys.exit(1)
            
   for opt, oa in opts:
      if opt == "--dir":
         startup.setHerbDir(oa)
         dirValue = oa
         dirCmdLine = "--dir " + dirValue + " "
         
      if opt == "--dest":
         destValue = oa
         destCmdLine = "--dest " + cmdLineQuote(destValue) + " "
   #//for

   startup.startup()
   startup.log.invoked(sys.argv)
   if debug:
      startup.log.comment("sys.argv = %s" % (sys.argv,))
      startup.log.comment("dirValue = %s" % dirValue)
      startup.log.comment("dirCmdLine = %s" % dirCmdLine)
      startup.log.comment("destValue = %s" % destValue)
      startup.log.comment("destCmdLine = %s" % destCmdLine)

   # If the initial line of stdin is a "From " line, remember it and
   # reflect it to stdout
   initialLine = sys.stdin.readline()
   initialFrom = initialLine[:5] == "From "
   if debug: 
      dOutFn = os.path.expanduser(debugOutputFn)
      fdebug = open(dOutFn, "a+")
      fdebug.write("\n- - - - - - initialFrom = %s\n" % initialFrom)
      fdebug.write(initialLine)

   #>>>>> get temporary filenames, for the call to herbrip
   messIncomingFn = os.tempnam("/tmp", "hpin_") 
   #messIncomingFn = os.path.expanduser("~/temp/hpin_test") 
   messProcessedFn = os.tempnam("/tmp", "hpin_") 

   #>>>>> write the (messIncomingFn) file
   f = open(messIncomingFn, "w")
   if debug:
      startup.log.comment("herbrip_pin: creating file <%s>, f=%s"
         % (messIncomingFn, f))
   if not initialFrom:
      f.write(initialLine)
   restOfStdin = sys.stdin.read()
   f.write(restOfStdin)
   if debug: 
      fdebug.write("&&&&& rest of stdin is:\n" + restOfStdin)
   f.close()

   #>>>>> invoke herbrip, to process the message
   cmd = "%s %s%s--in %s %s >/dev/null" % (
      os.path.join(herbripDir, "herbrip"), dirCmdLine, destCmdLine, 
      messIncomingFn, messProcessedFn)
   if debug: fdebug.write("***** CMD {%s}\n" % cmd)
   startup.log.comment("about to execute {%s}" % cmd)
   os.system(cmd)

   #>>>>> now send the processed message to stdout
   try:
      fproc = open(messProcessedFn, 'r')
   except:
      # it didn't create anything, so send stdin back to stdout
      sys.stdout.write(initialLine)
      sys.stdout.write(restOfStdin)
      if debug: fdebug.write("(herbrip didn't create output file)\n")
   else:
      # herbrip did create an output file, so we can send it to stdout.   
      # but first, add the 'From ' line if there was one
      if initialFrom:
         sys.stdout.write(initialLine)
      processedMessage = fproc.read()
      sys.stdout.write(processedMessage)
      if debug: fdebug.write(processedMessage)
      fproc.close()
      # we don't need the temporary output file any more
      os.remove(messProcessedFn)

   #>>>>> final cleanup
   # we don't need the temporary input file any more:
   os.remove(messIncomingFn)

   if debug: fdebug.close()



#---------------------------------------------------------------------

main()

#end herbrip_pin
