#!/usr/bin/env python

# herbrip = main module of Herbrip application
#
##########################################################
# Copyright (c) 2001 Philip Hunt. See COPYING for details
# of licensing information.
##########################################################

# Last altered: 19-Jul-2001
# History:
# 31-May-2001 PH: created
# 8-Jul-2001 PH: now using OpenSSL instead of GnuPG as encryption
#    engine

#***** 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

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

def startMessage():
   print "herbrip-%s. Copyright (c) 2001 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] --init 
      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         
"""   
   
def versionInfo(): 
   startMessage()
   #print 
   print "Herbrip version: %s" % HERBRIP_VERSION
   print "Complies with Herbivore 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

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

# initialize a herbivore system

def init():
   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)
   startup.startup()
   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)
   startup.startup()
   outgoing.processOut(fnEmailOut, fnEmailHerb)
   

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

def main():
   try:
      opts,args = getopt.getopt(sys.argv[1:], "",
         ["in", "out", "init", "version", "info", "usage", "dir="])
   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 == "--init": action = "--init"
      if opt == "--info": action = "--info"

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

      if opt == "--dir":
         startup.setHerbDir(oa)
   #//for
              
   if action == "--in":
      if len(args) != 2:
         print "Error: --in option must have 2 arguments"
         usage()
         sys.exit()
      startMessage()
      incomingEmail(args[0], args[1])
   elif action == "--out":
      if len(args) != 2:
         print "Error: --out option must have 2 arguments"
         usage()
         sys.exit()
      startMessage()
      outgoingEmail(args[0], args[1])
   elif action == "--init":
      init()
   elif action == "--info":
      info()
   else:
      # if anything unexpected happens, print a usage message then exit
      usage()
      sys.exit()



if __name__ == "__main__":
   main()


#end
