#!/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

	$DAEMON

	sleep 1

	/usr/sbin/glidegrd

}

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

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

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

	if [ $glidedPid -ne 0 ]
	then
		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
	else
		echo "\n glided is NOT found\n "
		#return 0
	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
