export PATH=$PATH:/usr/local/bin
passwd=""
GetPasswd ()
{
	passwd=`input_widget.oar "$1 Password:" ""`
	if `test -z $passwd`
	then
		exit
	fi
}

FileExists ()
{
	if `test -f "$1"`
	then
		if `ack_widget.oar "Overwrite?" "File $1 exists, overwrite?"`
		then
			return
		else
			exit
		fi	
	fi
}

if `test -z "$NLINES"` || `test -z "$FILE"`
then
	echo Archive $0 is corrupted!
	exit 1
fi
cd "$(dirname "$FILE")"
file="$(basename "$FILE")"

if `test -f "$FILE"` || `test -d "$FILE"`
then
	# re-encrypt
	passwd2=$passwd;
	passwd=""
	GetPasswd
	while `test "$passwd" != "$passwd2"`
	do
		passwd=""
		GetPasswd "Encrypt"
		passwd2=$passwd;
		passwd=""
		GetPasswd "Re-type"
	done
	
else		
	GetPasswd ""	
	FileExists "$FILE"
	FileExists "$FILE".nc
	
	tail -n +$NLINES "$0">"$file".tar.nc
	ncrypt -d -i "$file".tar.nc -k $passwd -o "$file".tar
	if `test "$?" -ne "0"`
	then
		output_widget.oar "Error" "Decryption of "$file".tar.nc failed"
		exit 1
	fi	
	tar -xf "$file".tar
	if `test "$?" -ne "0"`
	then
		output_widget.oar "Error" "unpacking of "$file".tar failed"
		exit 1
	fi	
	rm "$file".tar
	rm "$file".tar.nc
	case $file in
	    *.pdf )
	    	naboo_reader "$(pwd)/$file"
	        ;;
	    *.txt )
	        text_editor "$(pwd)/$file"
	        ;;
	    *)
	    	# we only decrypt. upon re-execution the file will only be re-encrypted
	    	exit
		;;
	esac
fi

let "NLINES--"
head -n $NLINES "$0" > "$0".tmp

if `test -f ".onyx/$file.sketch"`
then
	tar -c "$file" ".onyx/$file.sketch"> "$file".tar
else
	tar -c "$file" > "$file".tar
fi

if `test "$?" -ne "0"`
then
	output_widget.oar "Error" "Making a tar of $file failed"
	rm "$0".tmp
	exit 1
fi		

ncrypt -e -i "$file".tar -k $passwd -o "$file".tar.nc
if `test "$?" -ne "0"`
then
	output_widget.oar "Error" "Encryption of $file.tar failed"
	rm "$file".tar
	rm "$0".tmp
	exit 1
fi		
cat "$file".tar.nc >> "$0".tmp
rm "$file".tar.nc
rm "$file".tar
rm -rf "$file"
if `test -f ".onyx/$file.sketch"`
then
	rm ".onyx/$file.sketch"
fi
chmod +x "$0".tmp

# generate an update script
cat > updateScript.sh << EOF
#!/bin/sh
# Overwrite old file with new
if mv "$0.tmp" "$0"; then
  echo "Done. Update complete."
  rm \$0
else
  output_widget.oar "Error" "Oh-oh failed to update archive!"
fi
EOF

exec /bin/sh updateScript.sh
exit
