#!/bin/bash
OPTSTRING="dDsSiIrR"
while getopts $OPTSTRING flag; do
 case $flag in
  d|D)
   del=true
  ;;
  s)
   sign=true
   clear=true
  ;;
  S)
   sign=true
  ;;
  i|I)
   import=true
  ;;
  r|R)
   read=true
  ;;
 esac 
done 
shift $((OPTIND-1))
if [[ $import || $read ]];then DOC="$1";elif [[ $sign ]];then DOC="$2";else DOC="$3"; fi
if ! [[ $DOC ]];then DOC="​";del=true; fi #file not specified, insert zwsp and set del
if ! [[ $sign && $DOC ]] && ! [[ $1 && $2 ]] || [[ $sign ]] && ! [[ $1 ]] && ! [[ $import || $read ]];then
 echo "Usage: ~~ [OPTION]... {SENDER} {RECIPIENT}";
 echo "   or: ~~ [OPTION]... {SENDER} {RECIPIENT} {BUFFER_STRING}";
 echo "   or: ~~ [OPTION]... -s {SENDER} {BUFFER_STRING}";
 echo "<!> Enter SENDER and RECIPIENT, usage without BUFFER_STRING for unsaved input."
 echo "<!> Can be used with files on disk, or silently from within the terminal window."
 echo "<!> Use OPTION \"-d\" to delete plaintext from source, redundant when filename isn't specified."
 echo "<!> Use OPTION \"-s\" to clear-sign a document, which anyone can read and check against your public key."
 echo "<!> Use OPTION \"-S\" to sign a document with armor, which anyone can decrypt with your public key."
 echo "<!> Use OPTION \"-i\" to import a key into your keychain."
 echo "<!> Use OPTION \"-r\" to read PGP message from input."
 exit
fi

if [[ $import ]]; then nano "$DOC" && gpg --import "$DOC"
elif [[ $read ]]; then nano "$DOC" && gpg --decrypt "$DOC"
elif [[ $sign ]] then
 read -p "You are signing a document with key \"$1\" which can be viewed by anyone! Proceed (y/n)? " o
 if ! [[ $clear ]] then
   case "$o" in
    y|Y) nano "$DOC" && gpg --default-key "$1" --sign --armor "$DOC" && cat "$DOC.asc" && rm "$DOC.asc";;
    n|N) exit;;
      * ) echo "invalid user input (please try again)"; exit;;
     esac
  else
    case "$o" in
      y|Y) nano "$DOC" && gpg --default-key "$1" --clear-sign "$DOC" && cat "$DOC.asc" && rm "$DOC.asc";;
      n|N) exit;;
      * ) echo "invalid user input (please try again)"; exit;;
    esac
  fi
else
 nano "$DOC" && gpg --encrypt --default-key "$1" --sign --armor -r "$1" -r "$2" "$DOC" && cat "$DOC.asc" && rm "$DOC.asc"
fi;if [[ $del ]];then rm ./$DOC;exit;else
read -p "Delete plaintext \"$DOC\" (y/n)? " o
case "$o" in
  y|Y ) rm "./$DOC";;
  n|N ) exit;;
  * ) echo "invalid user input (document was not deleted)";;
esac
fi
