#!/bin/sh
### BEGIN INIT INFO
# Provides:        dlg-nm
# Required-Start:  $all
# Required-Stop:   $local_fs $network
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: DALiuGE Node Manager daemon
### END INIT INFO
#
#
# chkconfig: 2345 99 70
# description: Starts and stops the DALiuGE Node Manager as a daemon

# RH, Centos, Fedora configuration style
if [ -r /etc/sysconfig/dlg ]; then
	. /etc/sysconfig/dlg
# Debian, Ubuntu configuration style
elif [ -r /etc/default/dlg ]; then
	. /etc/default/dlg
else
	echo "Missing configuration file, cannot start DALiuGE" > /dev/stderr
	exit 1
fi

OPTS=""
if [ -n "${NM_HOST}" ]; then
	OPTS="$OPTS --host ${NM_HOST}"
fi
if [ -n "${NM_PORT}" ]; then
	OPTS="$OPTS --port ${NM_PORT}"
fi
if [ -n "${NM_LOGLEVEL}" ]; then
	case "${NM_LOGLEVEL}" in
		INFO)
			OPTS="$OPTS -v"
			;;
		DEBUG)
			OPTS="$OPTS -vv"
			;;
		*)
			echo "Unknown NM_LOGLEVEL value"
			exit 1
	esac
fi


# See how we were called.
RETVAL=0
case "$1" in
	start)

		# Prepare command-line options based on options file
		if [ "${NO_DLM}" = "YES" ]; then
			OPTS="$OPTS --no-dlm"
		fi
		if [ -n "${CWD}" ]; then
			cd "${CWD}"
			OPTS="$OPTS --cwd"
		fi

		# Launch the server and check right away if it started correctly
		su $USER -c "$DLG nm -d $OPTS"
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			echo "Successfully started the DALiuGE Node Manager, checking it started correctly"
			$0 status
			RETVAL=$?
			if [ $RETVAL -ne 0 ]; then
				echo "DALiuGE Node Manager didn't come up in time, shutting it down"
				$0 stop
			fi
		fi
		;;
	stop)
		echo "Shutting down DALiuGE Node Manager server"
		su $USER -c "$DLG nm -s"
		RETVAL=$?
		;;
	status)
		echo "Checking DALiuGE Node Manager status"
		su $USER -c "$DLG nm --status"
		RETVAL=$?
		;;
	restart)
		echo -n "Restarting DALiuGE Node Manager"
		$0 stop
		$0 start
		RETVAL=$?
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart}"
		RETVAL=1
esac

exit $RETVAL
