#!/bin/sh

if [ ! -x /usr/local/bin/check_free_space.oar ]
then
    exit 0
fi

if [ "$1" = "stop" -o "$1" = "restart" ]
then                                                                            
    #echo "Stopping the SDCard watchdog: "
	#doesn't work cleanly for trigger loop - but it'll be killed by removal of the fifo file
	for i in /var/run/check_free_space /var/run/sdc_watchdog_dbus /var/run/sdc_watchdog_trigger ; do cat $i | xargs kill && rm $i ; done
	rm /tmp/sdc_watchdog.fifo 
fi

if [ "$1" = "start" -o "$1" = "restart" ]                                       
then
	#need to sleep a while to make it work upon boot (probably dbus needs some time to start up)
	sleep 10
    #echo "Starting the SDCard watchdog: "
	#if we're not running already
	if [ -e /tmp/sdc_watchdog.fifo ] ; then exit ; fi
	
	#perform initial check
	mount | grep \/media\/sd | grep -v grep >/dev/null
	if [ $? == 0 ] ;   #mounted
	then 
		#i=`touch /media/sd/test.file.touch 2>&1` && rm /media/sd/test.file.touch || /usr/local/bin/output_widget.oar "SDCard write protected?" "$i" ;
		/usr/local/bin/check_free_space.oar >/dev/null &
		i=$!
		sleep 1 ; echo $i > /var/run/check_free_space
	fi
	
	#fetching messages from the dbus
	mkfifo /tmp/sdc_watchdog.fifo
	dbus-monitor --system "type='signal',sender=':1.0',interface='com.onyx.interface.system_manager',member='mountTreeSignal'" "type='signal',sender=':1.0',interface='com.onyx.interface.system_manager',member='sdCardChangedSignal'" > /tmp/sdc_watchdog.fifo &
	echo $! > /var/run/sdc_watchdog_dbus

	read p < /tmp/sdc_watchdog.fifo
	read p < /tmp/sdc_watchdog.fifo
	while read m ;
	do
		#what's the signal?
		signal=`echo $m | cut -d\; -f3 | cut -d= -f2`
		#echo Signal $signal
		if [ "$signal" == "sdCardChangedSignal" -o "$signal" == "mountTreeSignal" ] ;
		then
			read d < /tmp/sdc_watchdog.fifo
			echo $d | grep boolean | grep false >/dev/null
			if [ $? == 0 -a "$signal" == "sdCardChangedSignal" ] ; 
			then 
				#echo umounting SDCard
				sleep 2 ;
				umount /media/sd 2>/dev/null ; 
			fi
			echo $d | grep boolean | grep true >/dev/null
			if [ $? == 0 -a "$signal" == "mountTreeSignal" ]; 
			then 
				#echo checking free space
				#check whether the device is write mounted
				i=`touch /media/sd/test.file.touch 2>&1` && rm /media/sd/test.file.touch || /usr/local/bin/output_widget.oar "SDCard write protected?" "$i" & 
				#start space checker (if not running)
				ps xau | grep check_free_space | grep -v grep | grep \/bin\/sh >/dev/null
				if [ $? != 0 ] ; 
				then
					/usr/local/bin/check_free_space.oar >/dev/null &
					sleep 1
					echo $! > /var/run/check_free_space
				fi
			fi
		fi
	done < /tmp/sdc_watchdog.fifo &	
	echo $! > /var/run/sdc_watchdog_trigger
fi


