#!/usr/bin/env python
import os,sys
from optparse import *
from base64 import *

# Resolve this program's identity crisis.
prog=os.path.basename(sys.argv[0])
default_action=default=('decode','encode')[prog in ('base64','encode64')]

# Parse our command line.
op=OptionParser(add_help_option=False,usage="""
  encode64 [options] [input_file] [output_file]
  decode64 [options] [input_file] [output_file]

Description:
The encode64 program assumes --encode by default, while decode64 assumes
--decode. Otherwise, the programs are identical. Each one reads from either
standard input or the given input file and writes to standard output or the
given output file, encoding to base 64 or decoding from base 64 as it goes.

If only one file name is given on the command line, it is used for input or
output depending on whether standard input is being redirected. If it is then
the named file is used for output, and input data is read from standard input.
Otherwise, it is used for input, and output data is written to standard
output.""")
op.add_option('--help',dest='help_me',default=False,action='store_true',help="Show this message.")
op.add_option('-d','--decode',dest='action',default=default_action,action='store_const',const='decode',help="The input stream contains base-64 data that is to be decoded and sent to the output stream.")
op.add_option('-e','--encode',dest='action',default=default_action,action='store_const',const='encode',help="The input stream contains data that is to be base-64 encoded and sent to the output stream.")
opt,args=op.parse_args()
if opt.help_me:
  op.print_help()
  sys.exit(0)
if len(args)>2:
  op.print_help()
  sys.exit(1)

# Use command line arguments if available.
fin=fout=None
if len(args)==1:
  if not sys.stdin.isatty():
    fout=open(args[0],'w')
  else:
    fin=open(args[0],'rb')
elif len(args)==2:
  fin=open(args[0],'rb')
  fout=open(args[1],'wb')
# But reopen stdin and stdout in binary mode if we must use them.
if not fin:
  fin=os.fdopen(sys.stdin.fileno(),'rb')
if not fout:
  fout=os.fdopen(sys.stdout.fileno(),'ab')

if opt.action=='encode':
  encode(fin,fout)
else:
  decode(fin,fout)
