#!/bin/sh

source /var/packages/autorun/target/common

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

# default settings
TRIES=20
WAIT=0
# import our config
source /var/packages/autorun/target/config
MOUNTPATH=""
COUNT=0

# try to get the mount path
logInfo "device '$1' - inserted, trying to find mount point"
while ([ -z "$MOUNTPATH" ] && [ $COUNT -lt $TRIES ])
do
	MOUNTPATH=`/bin/mount 2>&1 | /bin/grep "/dev/$1" | /usr/bin/cut -d ' ' -f3`
	COUNT=$(($COUNT+1))
	/bin/sleep 1s
done

# abort when nothing is found
if [ -z "$MOUNTPATH" ]
then
	logInfo "device '$1' - unable to find mount point, aborting"
	exit 1
fi
logInfo "device '$1' - mount point '$MOUNTPATH' found"

# sleep some time because Synology does some crazy stuff like un- and remounting on SATA
/bin/sleep $WAIT

# is there a script on our drive?
if [ -x "$MOUNTPATH/$SCRIPT" ]
then
	# yes
	logInfo "device '$1' - script '$MOUNTPATH/$SCRIPT' found, executing"
	if [ $BEEP = "1" ]
	then
		beep 2
	fi
	if [ $LED = "1" ]
	then
		beep :
	fi

	# execute the script
	#   $1 - mount path
	#   $2 - device
	$MOUNTPATH/$SCRIPT $MOUNTPATH $1
	
	# save the result for later
	RESULT=$?

	# get the free space
        FREE=`/bin/df -h "$MOUNTPATH" | /bin/grep "$MOUNTPATH" | /usr/bin/awk '{ print $4 }'`

	# unmount when the result is 100
	if [ $RESULT = "100" ]
	then
		logInfo "device '$1' - script '$MOUNTPATH/$SCRIPT' finished ($FREE left on device), starting unmount"
		sleep 5
		sync
		umount $MOUNTPATH
		if [ $? -eq 0 ]
		then
			# and eject the drive 
			echo 1 > /sys/block/$1/device/delete
			logInfo "device '$1' - unmounted and ejected"
		else
			# abort on error
			logError "device '$1' - error while unmounting '$MOUNTPATH', aborting"
		        beepError
			exit 1
		fi
	else
		logInfo "device '$1' - script '$MOUNTPATH/$SCRIPT' finished ($FREE left on device), no further actions"
	fi
	if [ $BEEP = "1" ]
	then
		beep 2
	fi
	if [ $LED = "1" ]
	then
		beep 8
	fi
        if [ $NOTIFY = "1" ]
        then
		/usr/syno/bin/synodsmnotify $NOTIFYTARGET "autorun" "script finished, $FREE left on $MOUNTPATH"
        fi
else
	# no
	logInfo "device '$1' - no script '$MOUNTPATH/$SCRIPT' found, no further actions"
fi

exit 0
