#!/bin/sh

source /var/packages/autorun/target/common

# $1 - file name containing the password
if [ -z "$1" ]
then
	echo "incorrect '\$1' - aborting ..."
	exit 1
fi

# $2 - backup name
if [ -z "$2" ]
then
	echo "incorrect '\$2' - aborting ..."
	exit 1
fi

# $3 - external device from setup
if [ -z "$3" ]
then
	echo "incorrect '\$3' - aborting ..."
	exit 1
fi

# $4 - external device currently attached 
if [ -z "$4" ]
then
	echo "incorrect '\$4' - aborting ..."
	exit 1
fi

# $5 - eject?
if [ -z "$5" ]
then
	echo "incorrect '\$5' - aborting ..."
	exit 1
fi

# $6 - encrypt file names?
ENCFN="y"
if [ -n "$6" ]
then
	ENCFN=$6
fi

if [ $3 = $4 ]
then
	if [ -f "/var/packages/autorun/target/passwords/$1" ]
	then
		# load pwd
		PASSWD=`cat /var/packages/autorun/target/passwords/$1`

		# create directories
		if [ -d "$4/@LocalBackup@" ]
		then
			: # fine
		else
			logInfo "device '$4' - no directory for encrypted data found, creating new one"
			mkdir "$4/@LocalBackup@"
		fi
		if [ -d "$4/LocalBackup" ]
		then
			: # fine
		else
			logInfo "device '$4' - no directory for the backup found, creating new one"
			mkdir "$4/LocalBackup"
		fi

		# mount
		logInfo "device '$4' - mounting the encrypted file system"
		/usr/syno/sbin/mount.ecryptfs $4/@LocalBackup@ $4/LocalBackup -o ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_passthrough=n,no_sig_cache,ecryptfs_enable_filename_crypto=$ENCFN,passwd=$PASSWD

		# execute the backup
		/var/packages/autorun/target/localbackup "$2" "$3" "$4" "$5"

		# unmount
		logInfo "device '$4' - unmounting the encrypted file system"
		/bin/umount "$4/LocalBackup"
		if [ $? -eq 0 ]
		then
			: # everything fine
		else
			# abort on error
			logError "device '$4' - problem while unmounting the encrypted file system, aborting"
		        beepError
			exit 1
		fi
	else
		# abort on error
		logError "device '$4' - stored password missing for backup '$2', aborting"
        	beepError
	fi
else
	logError "device '$4' - parameters changed for local backup '$2' - '$3' expected but '$4' found, aborting"
       	beepError
fi

exit $5
