#!/bin/bash
#**********************************************************************************
#
# openITCOCKPIT V3 NodeJS Render Server
#
# Check file /usr/share/openitcockpit/app/LICENCE for licence information
#
#**********************************************************************************

### BEGIN INIT INFO
# Provides: nodejs_server
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Used by openITCOCKPIT to run JavaScript code on the server
# Description: Used by openITCOCKPIT to run JavaScript code on the server, liek rendering of ChartJS chrats
### END INIT INFO


set -e
set -u
i=0
DAEMON="/usr/bin/nodejs"
DAEMON_OPTS="/usr/share/openitcockpit/app/node/ChartRenderer.js"
PIDFILE=/var/run/nodejs_server.pid
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

if [ $# -lt 1 ]
then
	echo "$0 <start|stop|restart|status>"
	exit 1
fi

case $1 in
	start)
		echo "Starting openITCOCKPIT NodeJS Server"
		start-stop-daemon --start --pidfile $PIDFILE --make-pidfile --background --exec $DAEMON --chuid root:www-data -- $DAEMON_OPTS
	;;

	stop)
		echo "Stopping openITCOCKPIT NodeJS Server"
		start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
		while start-stop-daemon --pidfile $PIDFILE --status; do
			sleep .1
			if [ $i -ge 100 ]; then
				echo "openITCOCKPIT Push Notification Service stop failed"
				exit 1
			else
				i=$(( i + 1 ))
				echo -n "."
			fi
		done
	;;
	
	restart|reload|force-reload)
		echo "Restarting openITCOCKPIT NodeJS Server"
		$0 stop
		$0 start
	;;
	
	status)
		if start-stop-daemon --pidfile=$PIDFILE --status
		then
			PID=`cat $PIDFILE`
			echo "openITCOCKPIT NodeJS Server is running (pid $PID)."
			exit 0
		else
			echo "openITCOCKPIT NodeJS Server is not running"
			exit 3
		fi
		;;
	
	probe)
		echo restart
		exit 0
	;;
	
	*)
		echo "Unknown command $1."
		exit 1
	;;
esac
