#!/bin/bash

## created by Paul Miller <paul@tcimet.net>
## based on original PINEPGP scripts by Hakan Ardo <hakan@debian.org>

MSG=$1
TO=$2

if [ "$USEPGP5" = "true" ]; then
  USEPGP5=TRUE
fi
if [ -z "$PGPPATH" ]; then
  export PGPPATH=$HOME/.pgp
fi
if [ ! -d $PGPPATH ]; then
  /usr/lib/pinepgp/makekeys
fi

function check_address() {
  MAIL=$1
  FILE=$2
  RES=""
  if [ -f "$FILE" ]; then 
    for i in `cat $FILE`; do
      if [ ! -z "`echo $MAIL | grep $i`" ]; then
        RES="OK"
      fi
    done
  fi
}

DO="nothing"
check_address $TO "$HOME/.autocrypt"
if [ -z "$RES" ]; then
  if [ -f "$HOME/.autosign" ]; then
    check_address $TO "$HOME/.autosign"
    if [ -z "$RES" ]; then
      DO="sign"
    fi
  else
    check_address $TO "$HOME/.autonosign"
    if [ -z "$RES" ]; then
      DO="sign"
    fi
  fi
else
  DO="sign_encrypt"
fi

# required for fingering
. /usr/lib/pinepgp/.get_key

function menu() {
  echo
  echo "PINE/PGP send message"
  echo "---------------------"
  echo "s - sign"
  echo "r - encrypt"
  echo "e - sign & encrypt"
  echo "n - do nothing"
  echo "f - finger address"
  echo "c - cancel"
  echo
  echo -n "[default = $DO] Operation? "; read answer
  if [ ! -z `echo $answer | grep -i "f"` ]; then
    get_key
    menu
  fi
}

pgp=
pgp5=
menu
if [ ! -z `echo $answer | grep -i "c"` ]; then exit -1
elif [ ! -z `echo $answer | grep -i "n"` ]; then DO="nothing"
elif [ ! -z `echo $answer | grep -i "r"` ]; then DO="encrypt"
elif [ ! -z `echo $answer | grep -i "e"` ]; then DO="sign_encrypt"
elif [ ! -z `echo $answer | grep -i "s"` ]; then DO="sign"
elif [ ! -z "$answer" ]; then exit -1; fi

. /usr/lib/pinepgp/.$DO

clear
if [ "$USEPGP5" = "TRUE" ]; then
  $pgp5
else
  $pgp
fi
if [ ! $? = 0 ]; then
  exit -1
fi
mv $PGPPATH/tmp.msg $MSG
