#!/bin/bash

if [ "$USEPGP5" = "true" ]; then
  USEPGP5=TRUE
fi
if [ -z "$PGPPATH" ]; then
  export PGPPATH=$HOME/.pgp
fi
if [ ! -d $PGPPATH ]; then
  echo -n "PGP keys not found, would you like to create them (y/N)? "
  read answer
  if [ ! -z "`echo $answer | grep [yY]`" ]; then
    /usr/lib/pinepgp/makekeys
  fi
  if [ ! -d $PGPPATH ]; then
    note="Unable to check signature, PGP keys could not be found."
    echo >> $1
    echo "--" >> $1
    echo "$note" >> $1
    echo "$note" >> $2
    exit 0
  fi
fi

starttext="-----BEGIN PGP DECRYPTED MESSAGE-----"
endtext="-----END PGP DECRYPTED MESSAGE-----"

TST=`grep -- "-----BEGIN PGP" $1`
if [ "$TST" = "$starttext" ]; then
    # exit without modifying the file
    echo 'Already decrypted message.' > $2
    exit 0
fi

HEAD=`sed -n -e '1,/-----BEGIN PGP/!d' -e '/-----BEGIN PGP/!p' $1`
TAIL=`sed -n -e '/-----END PGP/,$!d' -e '/-----END PGP/!p' $1`

# clear HEAD if there is no header
FIRST=`head -1 $1|grep -- "-----BEGIN PGP"`
if [ ! -z "$FIRST" ]; then
  HEAD=""
fi

# make sure tmp files are gone; otherwise it will freeze if they exist
rm -f $PGPPATH/tmp.check

if [ "$USEPGP5" = "TRUE" ]; then
  . /usr/lib/pinepgp/.pgp5.0
else
  . /usr/lib/pinepgp/.pgp
fi
