#!/bin/sh

source /var/packages/autorun/target/common

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

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

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

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

if [ $2 = $3 ]
then
	# wait some more time to ensure the backup will run
	sleep 10s
	logInfo "device '$3' - local backup '$1' started"
	/usr/syno/bin/synobackup --backup "$1"
	
	# we have to poll for the end - wait until the process is finished
	sleep 60
	while [ "$(/bin/pidof synolocalbkp)" ]
	do
		sleep 60
	done
	logInfo "device '$3' - local backup '$1' finished"
else
	logError "device '$3' - parameters changed for local backup '$1' - '$2' expected but '$3' found, aborting"
       	beepError
fi

exit $4
