#!/bin/bash

export NODE_PATH=/usr/lib/node_modules:$NODE_PATH

NAME=lightning-rod
FOLDER=$NODE_PATH/@mdslab/iotronic-lightning-rod
DAEMON=$FOLDER/lr-server.js
DESC=lightning-rod
LOGFILE="/var/log/iotronic/lightning-rod.log"
PIDFILE="/var/run/s4t-lightning-rod.pid"


test -x $DAEMON || exit 0
set -e

. /lib/lsb/init-functions

MYPID=`ps aux | grep $DAEMON | grep -v grep | awk {'print $2'}`


case "$1" in

        start)
                echo -e "Starting $DESC ..."

		if [[ -z $MYPID ]];
		then
			start-stop-daemon --start -d $FOLDER --quiet --make-pidfile --pidfile $PIDFILE --exec $DAEMON >> /dev/null & # ${LOGFILE} &

		elif [[ -s $PIDFILE && `cat $PIDFILE` == $MYPID ]];
		then
			echo -e "Already started!"

		else
			echo $MYPID > $PIDFILE
			echo -e "Already started!"
		fi
		;;

        stop)

                echo -e "Stopping $DESC ..."
		if [[ -s $PIDFILE && `cat $PIDFILE` == $MYPID ]];
		then
	                kill -9 `cat $PIDFILE`
			rm $PIDFILE
		else
			echo -e "inactive!"
		fi

		;;

        restart)

                echo -e "Restarting $DESC ..."
		if [[ -s $PIDFILE && `cat $PIDFILE` == $MYPID ]];
		then
	                kill -9 `cat $PIDFILE`
			rm $PIDFILE
		fi
                sleep 2
                #start-stop-daemon --start -d $FOLDER --quiet --make-pidfile --pidfile $PIDFILE --exec $DAEMON >> ${LOGFILE} 2>&1   || true &
		        start-stop-daemon --start -d $FOLDER --quiet --make-pidfile --pidfile $PIDFILE --exec $DAEMON >> /dev/null & #  ${LOGFILE} &

		;;

        status)

                echo -e "$DESC status..."
		if [[ -z $MYPID ]];
		then
			echo -e "inactive!"
		else
	                echo -e "PID: "`cat $PIDFILE`
		fi
		;;

        *)
                N=/etc/init.d/$NAME
                echo "Usage: $N {start|stop|restart|status}" >&2
                exit 1
                ;;
esac

exit 0
