#!/bin/sh

### BEGIN INIT INFO
# Provides:          phidgetwebservice
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Should-Start:      avahi avahi-daemon phidgetsbcwebif
# Should-Stop:       avahi avahi-daemon
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Phidget Webservice
# Description:       Phidget Webservice for controlling Phidgets over the network.
### END INIT INFO

DESC="Phidget Webservice"
NAME=phidgetwebservice
BIN=phidgetwebservice21
DAEMON=/usr/bin/$BIN
PIDFILE=/var/run/$NAME.pid
CFG=/etc/default/$NAME

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

# load config
pws_enabled="true"
pws_port="5001"
pws_serverid=""
pws_password=""
[ -f $CFG ] && . $CFG

start() {
	[ -z "$pws_port" ] || OPTIONS="-v -p $pws_port "
	[ -z "$pws_password" ] || OPTIONS="$OPTIONS-P $pws_password "

	if [ -z "$pws_serverid" ]; then
		OPTIONS="$OPTIONS -n $( hostname )"
	else
		OPTIONS="$OPTIONS -n $pws_serverid"
	fi
	
	echo -n "Starting $DESC: "
	start-stop-daemon --start --quiet \
 	  --make-pidfile --pidfile $PIDFILE --background \
 	  --startas /bin/bash -- -c "exec $DAEMON $OPTIONS >> /var/log/$NAME.log 2>&1" && echo "OK" || echo "ALREADY RUNNING"
	#start-stop-daemon -S -b -q -p $PIDFILE -m -x $DAEMON -- $OPTIONS && echo "OK" || echo "ALREADY RUNNING"
}

stop() {
	echo -n "Stopping $DESC: "
	if [ -f ${PIDFILE} ] ; then
		start-stop-daemon -K -q -p $PIDFILE -x $DAEMON && echo "OK" || echo "NOT RUNNING"
		rm -f ${PIDFILE}
	else
		echo "${PIDFILE} not found"
	fi
}

stopwait() {
	echo -n "Stopping $DESC: "
	if [ -f ${PIDFILE} ] ; then
		PID=`cat ${PIDFILE}`
		start-stop-daemon -K -q -p $PIDFILE -x $DAEMON && echo "OK" || echo "NOT RUNNING"
		# wait for process to exit
		while kill -0 ${PID} 2> /dev/null; do sleep 1; done
		rm -f ${PIDFILE}
	else
		echo "${PIDFILE} not found"
	fi
}

reload() {
	if [ -f ${PIDFILE} ] && kill -0 $(cat ${PIDFILE}) ; then
		echo -n "Reloading ${DESC}: "
		stopwait
		start
	fi
}

case "$1" in
  forcestart)
	start
	;;
  start)
	if [ "$pws_enabled" = "true" ]; then
		start
	else
		echo "Not starting Phidget Webservice."
		exit 0
	fi
	;;
  stop)
	stop
	;;
  reload)
	reload
	;;
  restart|force-reload)
	stopwait
	if [ "$pws_enabled" = "true" ]; then
		start
	else
		echo "Not starting Phidget Webservice."
		exit 0
	fi
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
esac

exit 0
