#!/bin/sh
### BEGIN INIT INFO
# Provides:          cirque corporation
# Required-Start:    $remote_fs dbus
# Required-Stop:     $remote_fs dbus
# Should-Start:	     $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: GlidePoint Daemon
# Description:       glide daemon for configuring alps touch pad  
#                    automatically
### END INIT INFO

#set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="GlidePoint Touch Pad Glide Daemon"
NAME="glided"
DAEMON="/usr/sbin/$NAME"
#SCRIPTNAME=/etc/init.d/$NAME
SCRIPTNAME=/etc/init.d/glidepoint


glidedPid=0
glidegrdPid=0

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

#. /lib/lsb/init-functions

# Include glide-daemon defaults if available.
test -f /etc/default/glided && . /etc/default/glided


#
#       Function that starts the daemon/service.
#glideusdCommand="glideusd"
pidFile="$HOME/.glideusd.pid"
daemonuser=$HOME
maxShutdownTime=15
glideusdDir="/usr/bin"
PIDFILE=".glideusd.pid"

glideusdPid=0
d_start() {
	
	local input="$(lsmod | grep uinput | cut -d " " -f 1)"

	if [ "$input" != "uinput" ] 
        then
		echo "load uinput..."
		sudo modprobe uinput 
	else
		echo "uinput is loaded"
	fi
#sometimes config file of lightdm will be set to default, so we have to add command to it at every boot time	
	lightdmCheck="$(cat /etc/lightdm/lightdm.conf | grep glidepoint_daemon)"
	if [ -d /etc/lightdm -a "$lightdmCheck" = "" ]
	then
		echo 'greeter-setup-script=/usr/sbin/glidepoint_daemon' >> /etc/lightdm/lightdm.conf
	fi
	
	glidedPid="$(ps -C "glided" --no-headers -o pid)"
	if [ "$glidedPid" = "" ]
	then
#		$DAEMON
		echo "\n Run glided"
	else
		echo "\n glided: $glidedPid is already running!"
	fi

	sleep 1

	glidegrdPid="$(ps -C "glidegrd" --no-headers -o pid)"
	if [ "$glidegrdPid" = "" ]
	then
#		/usr/sbin/glidegrd
		echo "\n Run glidegrd"
	else
		echo "\n glidegrd: $glidegrdPid is already running!"
	fi

}

#
#       Function that stops the daemon/service.
#
d_stop() {
	glidegrdPid="$(ps -C "glidegrd" --no-headers -o pid)"

	if [ "$glidegrdPid" = "" ]
	then
		echo "\n glidegrd is NOT found\n "
	else
		#return $glidegrdPid
		echo "\n sending SIGKILL to kill glidegrd: $glidegrdPid...."
		#kill -s KILL $glidegrdPid 
		sudo kill -9 $glidegrdPid
	fi  

	glidedPid="$(ps -C "glided" --no-headers -o pid)"
	echo "\n glidedPid is: "
	echo $glidedPid

	if [ "$glidedPid" = "" ]
	then
		echo "\n glided is NOT found\n "
		#return 0
	else
		echo "\n glided is found, its PID = $glidedPid \n "
		#return $glideusdPid
		echo "\n sending SIGKILL to kill glideusd: $glidedPid...."
		#kill -s KILL $glidedPid 
		sudo kill -9 $glidedPid
	fi      
}

case "$1" in
    start)
        d_start
        ;;
    stop)
        d_stop
        ;;

    *)
	#d_start
        #echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|reload}" >&2
        ;;
esac

exit 0
