#!/usr/bin/env python

# herbrip_csm = Herbrip capture sendmail input
#
###############################################################
# Copyright (c) 2001,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: 8-Feb-2002
# History:
# 24-Jan-2002: created
#
# 8-Feb-2002 PH: If no recipients are specified on the command line, 
# uses the To:, Cc: and Bcc: lines to determine recipients


"""***
herbrip_csm has an interface like sendmail. The MUA can be set up
to push outgoing email to herbrip_csm instead of sendmail; herbrip_csm
then processes this and sends it to the final output.

Reads in the message from stdin, the recipient or recipients from 
the command line arguments, and sends it out to the location specified 
in (dest).

If no recipients are specified, it uses the contents of the To:, Cc:
and Bcc: lines in the message to determine the recipients.
***"""

#***** python standard libraries:
import sys
import getopt

#***** phil's libraries:
#import utility
import mailheader

#***** part of Herbrip:
#from herb_globals import *
import startup
import outgoing

debug = 1 # debugging this module?

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

def main():
   if debug: print "herbrip_csm"  
   # --dir, --dest options as with herbrip:

   try:
      if debug: print "herbrip_csm (2) argv=%s" % (sys.argv,)  
      opts,args = getopt.getopt(sys.argv[1:], "",
         ["dir=", "dest="])
      if debug: print "herbrip_csm (3) opts=%s\nargs=%s" %(opts, args)   
   except:
      # print help info, and exit
      #usage()
      sys.exit(1)
            
   for opt, oa in opts:
      if opt == "--dir":
         startup.setHerbDir(oa)
         
      if opt == "--dest":
         if debug: print "$$$ dest is [%s] $$$" % oa  
         startup.overrideConfig['dest'] = oa 
   #//for

   startup.startup()
   startup.log.invoked(sys.argv)

   # read in message
   messStr = sys.stdin.read()
   mess = mailheader.makeMailFromString(messStr)

   recipients = args
   if len(recipients) < 1: 
      if debug: startup.log.comment("no recipients, using To, Cc, Bcc")

      startup.log.message("o", mess)
      outgoing.processOutDestMail(mess)
      
   else:
      # get a list of recipients real names and their email addresses
      recipNameAddrs = [ ]
      for r in recipients:
         recipNameAddrs.append(['', r])
      if debug: print recipNameAddrs

      startup.log.message("o", mess)
      outgoing.processForMulti(mess, recipNameAddrs)

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

main()

#end herbrip_csm
