#!/bin/bash

###############################
#	VARIABLES

#Get current working directory
wdir=/usr/lib/linuxmint/mint-fm2

#Monitored directory
appdir=/usr/share/applications

#Root lock
rootlock=/tmp/rootlock

#Ciao trigger dir
ciaodir=/etc/ciao-trigger

##############################


#kill appwatch daemon if running
ps -eo pid,user,args --sort pid | grep "inotifywait -q -m -r --format %e %w%f -e create -e delete $appdir" | sed -e '/grep/ d' | while read line
do
	if [ ! -z "$line" ]
	then
#		echo "daemon found $line"
		pid=`echo $line | cut -d ' ' -f1`
#		echo "killing $pid"
		kill $pid
	fi
done

#kill ciaowatch daemon if running
ps -eo pid,user,args --sort pid | grep "inotifywait -q -m -r --format %f -e create $ciaodir" | sed -e '/grep/ d' | while read line
do
	if [ ! -z "$line" ]
	then
#		echo "daemon found $line"
		pid=`echo $line | cut -d ' ' -f1`
#		echo "killing $pid"
		kill $pid
	fi
done

#remove root lock
if [ -f $rootlock ]
then
	rm $rootlock
fi

#check for ciao trigger dir and remove any triggers
if [ -d $ciaodir ]
then 
	rm -rf $ciaodir/*
	chmod 777 $ciaodir
else
	mkdir $ciaodir
	chmod 777 $ciaodir
fi

###############################
#Now that we have a clean slate, we consider start|stop parameters

case "$1" in

#First start
  start|restart)


###############################
#	APP WATCH FUNCTION

function appwatch {

#inotify watch

inotifywait -q -m -r --format '%e %w%f' -e create -e delete $appdir | while read line
do

#Check if other entries are being processed	
	while [ -f $rootlock ]
	do
		echo "Entries being processed"
		sleep 2
	done
#/End of check and wait

		appfile=`echo $line | grep .desktop`
		if [ ! -z "$appfile" ]
		then
		touch $rootlock
		$wdir/./postchange $appfile
		rm $rootlock
		fi

done
}

###############################


###############################
#	CIAO WATCH FUNCTION

function ciaowatch {

inotifywait -q -m -r --format '%f' -e create $ciaodir | while read line
do

#shutdown
if [ "$line" = "shutdown" ]
then
	rm -rf $ciaodir/*
	/sbin/usplash &
	shutdown -h now
fi

#restart
if [ "$line" = "restart" ]
then
	rm -rf $ciaodir/*
	/sbin/usplash &
	shutdown -r now
fi

#suspend
if [ "$line" = "suspend" ]
then
	rm -rf $ciaodir/*
	pmi action sleep
fi

#hibernate
if [ "$line" = "hibernate" ]
then
	rm -rf $ciaodir/*
	pmi action hibernate
fi


done
}
###############################

#Run functions
appwatch &
ciaowatch &
echo "mint-fm2 (re)started"
exit
	;;

#Second, stop
  stop)
  	echo "mint-fm2 stopped"
  	exit
  	;;

#Third, usage instructions
  *)
	echo "Usage: mfmrootdaemon [start|stop|restart]" >&2
	exit 3
	;;
esac

exit
