#!/usr/bin/env python

# herbrip = main module of Herbrip application
#
###############################################################
# 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: 27-Jan-2002
# History:
# 31-May-2001 PH: created
# 8-Jul-2001 PH: now using OpenSSL instead of GnuPG as encryption
#    engine
# 18-Nov-2001 PH: adding --outp option (output to other program)
# changing --init to --create
#
# 24-Jan-2002: changing --outp option to --outd

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

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

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

debug = 0 # debugging this module?

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

def startMessage():
   print "herbrip-%s. Copyright (c) 1999-2002 Philip Hunt."\
      % HERBRIP_VERSION

def usageExp():
   startMessage()
   print """Herbrip is a command-line program for encrypting/decrypting email 
with the Herbivore encryption protocol.
"""

def usage():
   print """Usage:
   herbrip [options] --in email.in email.pt
      processes incoming email <email.in>, creating plaintext version 
      in <email.pt>
      
   herbrip [options] --out email.out email.herb
      processes outgoing email <email.out>, outputting result into 
      <email.herb> 
      
   herbrip [options] --outd email.out 
      processes outgoing email <email.out>, sending result to a
      destination specified in config file or --dest
      
   herbrip [options] --create
      initializes the Herbrip system, creating directories and files.
      Any existing system at that directory is deleted. 
      
   herbrip [options] --info
      outputs various information
      
   herbrip --version 
      outputs version information
      
   herbrip --usage
      outputs usage information   
      
Options are:
   --dir someDirectory
      causes herbrip to use <someDirectory> as its data directory;
      the default is ~/.herbivore  
      
   --dest destinationOfOutput
      Overrides the 'dest' variable in the <config> file.          
"""   
   
def versionInfo(): 
   startMessage()
   #print 
   print "Herbrip version: %s" % HERBRIP_VERSION
   print "Complies with Herbivore protocol version: %s" % HERBIVORE_VERSION
  

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

# --info option.
# deliver information to the user

def info():
   startMessage()
   startup.startup()
   print """
Herbivore protocol version: %s 
Herbivore directory: %s  
secret key file: %s
public key file: %s""" % (HERBIVORE_VERSION, startup.getHerbDir(), 
       startup.getSecretPn(), startup.getPublicPn())
       
   # print public keys:
   addrs = startup.publicKeys.keys()
   addrs.sort()
   i = 1
   numPK = len(addrs)
   plural = ""
   if numPK != 1: plural = "s"
   further = "."
   if numPK > 0: further = ":"
   print "user has %d public key%s%s" % (numPK, plural, further)
   for addr in addrs:
      v = startup.publicKeys[addr]
      pubKey = v['key'][:60]
      name = v['name']
      print '<%s> (%s)\n   %s..' % (addr, name, pubKey)
      i += 1
      
   # print config values 
   print "Configuration values:"
   configKeys = startup.config.keys()
   configKeys.sort()
   for k in configKeys:
      v = startup.config[k]
      print "   %s = %s" % (k, repr(v))  

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

# initialize a herbivore system

def create():
   print "herbrip: initializing at %s ..." % startup.getHerbDir()
   initial.forceInit("", "")

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

# process incoming email, reading from filename (fnEmailIn) and
# writing plaintext to (fnEmailPt)

def incomingEmail(fnEmailIn, fnEmailPt):
   if debug: 
      print "** incomingEmail %s -> %s" \
         % (fnEmailIn, fnEmailPt)
   incoming.processIn(fnEmailIn, fnEmailPt)
   
   # output the public key file (for debugging)
   if debug:
      utility.outPrettyPickle(startup.getPublicPn())

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

# process outgoing email, reading from filename (fnEmailOut) and
# writing herbivorized result to (fnEmailHerb)

def outgoingEmail(fnEmailOut, fnEmailHerb):
   if debug: 
      print "** outgoingEmail %s -> %s" \
         % (fnEmailOut, fnEmailHerb)
   outgoing.processOut(fnEmailOut, fnEmailHerb)
   
#---------------------------------------------------------------------
   
# process outgoing email, sending output to somewhere which is
# defined in the 'dest' variable of the config file, or in the --dest
# command line argument

def outgoingEmailDest(fnEmailOut):
   if debug: 
      print "** outgoingEmailDest %s" % fnEmailOut
   outgoing.processOutDest(fnEmailOut)   

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

def main():
   try:
      opts,args = getopt.getopt(sys.argv[1:], "",
         ["in", "out", "outd", "create", "version", "info", "usage", 
          "dir=", "dest="])
   except:
      # print help info, and exit
      usage()
      sys.exit(1)
      
   # if nothing intelligible specified, default to printing usage
   # information:
   action = "--usage" 
      
   for opt, oa in opts:
      if opt == "--in": action = "--in"
      if opt == "--out": action = "--out"
      if opt == "--outd": action = "--outd"
      if opt == "--create": action = "--create"
      if opt == "--info": action = "--info"

      if opt == "--usage":
         usageExp()
         usage()
         sys.exit()
         
      if opt == "--version":
         versionInfo()
         sys.exit()

      if opt == "--dir":
         startup.setHerbDir(oa)
         
      if opt == "--dest":
         if debug: print "$$$ dest is [%s] $$$" % oa  
         startup.overrideConfig['dest'] = oa 
   #//for
              
   if action == "--in":
      if len(args) != 2:
         print "Error: --in option must have 2 arguments"
         usage()
         sys.exit()
      startMessage()
      startup.startup()
      startup.log.invoked(sys.argv)
      incomingEmail(args[0], args[1])
   elif action == "--out":
      if len(args) != 2:
         print "Error: --out option must have 2 arguments"
         usage()
         sys.exit()
      startMessage()
      startup.startup()
      startup.log.invoked(sys.argv)
      outgoingEmail(args[0], args[1])
   elif action == "--outd":
      if len(args) != 1:
         print "Error: --outd option must have 1 argument"
         usage()
         sys.exit()
      startMessage()
      startup.startup()
      startup.log.invoked(sys.argv)
      outgoingEmailDest(args[0])      
   elif action == "--create":
      create()
   elif action == "--info":
      info()
   else:
      # if anything unexpected happens, print a usage message then exit
      usage()
      sys.exit()



if __name__ == "__main__":
   main()


#end
