#!/bin/dash
# gui for scrypt encrypt/decrypt, re-written for Fatdog 700
# (C) James Budiono 2015
#
# $1-optional filename

# $1-title $2-message
msg() {
	Xdialog --title "$1" --infobox "$2" 0 0 10000
}

# input: file, pw1, pw2 
interactive() {
	if ans="$(Xdialog --title "scrypt GUI" --separator "\n" --stdout \
	--password --password --3inputsbox \
	"Encrypt/decrypt file with scrypt. 
	File that ends with '.sfe' will be decrypted,
	all others will be encrypted." 0 0 \
	"Drag the file to be encrypted/decrypted here ↓" "$file" \
	"Password (mininum 8 characters)" "$pw1" \
	"Confirm Password (only needed for encryption)" "$pw2")"; then
		OIFS="$IFS"; IFS="
"; set -- $ans; file="$1"; pw1="$2"; pw2="$3"; IFS="$OIFS"
		if ! [ -e "$file" ]; then
			msg "Error" "$file does not exist."
			interactive
		fi
		case "$file" in
			*.sfe) # decrypt
				if ! echo "$pw1" | scrypt dec "$file" "${file%.sfe}"; then
					msg "Error" "Failed decrypting $file." 
					interactive
				else
					msg "Success" "$1 decrypted successfully." 
				fi ;;
			*) # encrypt
				if ! [ "$pw1" = "$pw2" ]; then
					msg "Error" "Passwords don't match."
					interactive
				elif [ ${#pw1} -lt 8 ]; then
					msg "Error" "Password is less than 8 characters."
					interactive
				elif ! printf "%s\n%s\n" "$pw1" "$pw2" | scrypt enc "$file" "${file}.sfe"; then
					msg "Error" "Failed encrypting $file." 
					interactive
				fi ;;
		esac
	fi
}

### main ###
[ "$DISPLAY" ] || exit 1
type scrypt > /dev/null || {
	Xdialog --title "Error" --infobox "Cannot find scrypt" 0 0 10000
	exit 1
}
file="$1" pw1="" pw2=""
interactive
