#!/bin/sh
#shuber, 2008-10-18
#
# This script does a decrypt-edit-encrypt cycle with gpg and OpenOffice.
# The concrete editing program (ooffice) can be set by the variable
# $CMD. The detection if the file has been altered is done by a hash sum
# algorithm which can be set by $SUMCMD.
#
# Changelog:
#    * 2008-10-18   Initial version
#    * 2008-10-19   Introducing a CRYPTID variable
#                   Checking if crypted file has same checksum
#    * 2010-10-23   ooffice only spawns OpenOffice and gives control back
#                   to shell. Hence, we have to wait for pid now.


CMD="ooffice"
SUMCMD="sha1sum"
CRYPTID="shuber2@gmail.com"


#No valid invocation
if [ $# -ne 1 ]
then
	echo "Usage: $CMD-gpg <gpg-file>"
	exit -1
fi


#The corresponding gpg-file
gpgfile=$1

if [ ! -f "$gpgfile" ]
then
	echo "\`$gpgfile\` does not exist..."
else
	echo "Opening \`$gpgfile\`..."
fi



#Search for filename to to encrypt file to...
uncryptfilePost=${gpgfile%%.gpg}
i=1
uncryptfile="$i.$uncryptfilePost"

while [ -f "$uncryptfile" ]
do
	let "i = $i + 1"
	uncryptfile="$i.$uncryptfilePost"
done


echo "Uncrypt \`$gpgfile\` to  \`$uncryptfile\`..."



#Decrypt file and get checksum...
gpg  --output "$uncryptfile" --decrypt "$gpgfile"
hsumpre=`$SUMCMD "$uncryptfile" | awk '{ print $1 }'`
echo "Checksum is '$hsumpre'."


#Edit file and get checksum of altered file
$CMD "$uncryptfile"
pid=`lsof | grep "$uncryptfile" | cut -d ' ' -f 2`
echo "wait for pid: $pid"
while [ -n "`ps | grep $pid`" ] ; do
	sleep 1
done


hsumpost=`$SUMCMD "$uncryptfile" | awk '{ print $1 }'`
echo "Checksum is '$hsumpost'."


#Check if file has been altered
if [ "$hsumpost" != "$hsumpre" ]
then
	gpg --output "$gpgfile" -r "$CRYPTID" --encrypt "$uncryptfile" 

	#Get checksum of crypted version
	hsumcrypt=`gpg --decrypt $gpgfile | $SUMCMD | awk '{ print $1 }'`
	echo "Checksum of crypted file is '$hsumcrypt'"

	if [ "$hsumpost" != "$hsumcrypt" ]
	then
		echo ""
		echo "*** WARNING ***"
		echo "*** WARNING ***   Encrypted file \`$gpgfile\` leads to different checksum."
		echo "*** WARNING ***   Not removing unencrypted file \`$uncryptfile\`."
		echo "*** WARNING ***"
		echo ""

		exit -1
	fi

else
	echo "No changes. Skip re-encrypting"
fi




#Remove old file...
rm -i "$uncryptfile"


#File not removed!?
if [ -f "$uncryptfile" ]
then
	echo ""
	echo "*** WARNING ***"
	echo "*** WARNING ***   Unencrypted file \`$uncryptfile\` not removed!"
	echo "*** WARNING ***"
	echo ""
fi

