#!/bin/sh
# admin PGP keys in Mutt, (C) M. Andreoli, for muLinux
# Is called within the mutt macro "k"

> /tmp/mutt.rc
chmod ugo+rw /tmp/mutt.rc

TMP=/tmp/filter$$
H=/tmp/H$$
B=/tmp/B$$

# Functions

pre="cat > $TMP; cat $TMP|formail -X '' > $H;\
cat $TMP|formail -I '' > $B"
post="rm ${TMP} $B $H"

bright()
{
echo -e "\033[01m"
}
normal()
{
echo -e "\033[0m"
}

Store()
{
clear
bright
cat <<END
The message gets saved in this mailbox: [`basename $mbox`]. 
Please, after processing, change mailbox using the 'c' macro,
if you wish to check it.
END
normal
cat > /tmp/mutt.rc <<END
push "|${pre};${filter}>>${mbox};${post}\nd"
END
exit 0
}

Return()
{
echo "$@" > /tmp/mutt.rc
exit 0
}

#---------
# Main
#----------

# check the key db

if [ ! -d $HOME/.pgp ] ; then
	clear
	bright
	echo "Generating the PGP data-base"
	normal
	mkdir $HOME/.pgp
	pgp -kg
	clear
fi		


echo " -- (Rustic) Cryptographic Menu --"
case $0 in
*key-compose*)
cat <<END
noMIME:   [os] old-way-sign [oe] old-way-encrypt
END
;;
*)
cat <<END
KEYS:     e[x]tract-from [m]ail-to [g]enerate [r]emove [l]ist [c]heck-db
STORE:    [es] encrypted-and-store
noMIME:   [od] old-way-decrypt [oc] old-way-check-sign
END
;;
esac
echo -n "q)uit :"

read op 

case $op in
q)
	echo "Excellent!"
	exit 0
	;;
os)	# sign without MIME (only compose menu)
	Return 'push "Fpgp -fsat\ny"' 
	;;
oe)	# encrypt without MIME (only compose menu)
	Return 'push "Fpgp -feat\ny"' 
	;;
od)	# decrypt plain-text PGP 
        mbox=$HOME/Mail/decrypted
        filter="(cat $H; cat $B | pgp -f) |\
        formail -i 'X-pgp-decrypted'"
        Store
	;;
oc)     # check-signature in plain-text PGP
        mbox=$HOME/Mail/checked
        filter="(cat $H; cat $B | pgp -f) |\
        formail -i 'X-pgp-checked'"
        Store
        ;;

e)	# PGP encrypt and save in the mbox mailbox	
        filter="(cat $H; cat $B | pgp -feat) |\
        formail -i 'Content-Type: application/pgp; format=text; \
        x-action=encrypt'"
        mbox=$HOME/Mail/encrypted
	Store
	;;
x)	# extract the public key from a KEY-MESSAGE MIME
	Return "push ^K"
	;;
m)	# mail my public key to someone
	Return "push \ek"
	;;
l)	# list my keyring
	pgp -kv 2>/dev/null 
	;;
g)	# generate new keys
	clear
	pgp -kg
	;;
r)	# remove some key from data-base
	clear
	pgp -kv 2>/dev/null 
	echo
	pgp -kr
	;;
c)	# check key data-base
	clear
	pgp -kc
	;;
esac
echo

# End
