#! /bin/bash
#
# v6d          Start/Stop the v6 licensing daemon
#
# chkconfig: 2345 21 77
# description: v6 daemon
# processname: v6d
# pidfile: /var/run/v6d.pid

# Source function library.
. /etc/init.d/functions

# v6 licensing daemon

# location of the executable:
V6D="/opt/xensource/libexec/v6d"

# pidfile:
PID_FILE="/var/run/v6d.pid"

# lock file
SUBSYS_FILE="/var/lock/subsys/v6d"

start() {
	echo -n $"Starting the v6 licensing daemon: "
	
	if [ -e ${SUBSYS_FILE} ]; then
		if [ -e ${PID_FILE} ] && [ -e /proc/`cat ${PID_FILE}` ]; then
			echo -n $"cannot start v6d: already running."
			failure $"cannot start v6d: already running."
			echo
			return 1
		fi
	fi
	
	${V6D} -daemon -pidfile ${PID_FILE} >/dev/null 2>&1 </dev/null

	MAX_RETRIES=30
	RETRY=0
	while [ ${RETRY} -lt ${MAX_RETRIES} ]; do
		PID=$(pidof v6d)
		kill -0 ${PID} 2> /dev/null
		if [ $? -eq 0 ]; then
			touch ${SUBSYS_FILE}
			success
			echo
			return 0
		fi
		sleep 1
		echo -n .
		RETRY=$(( ${RETRY} + 1 ))
	done
	echo -n $"failed to start v6d."
	failure $"failed to start v6d."
	killproc v6d
	rm -f ${SUBSYS_FILE} ${PID_FILE}
	echo
	return 1
}

stop() {
	echo -n $"Stopping the v6 licensing daemon: "

	if [ ! -e ${SUBSYS_FILE} ]; then
		echo -n $"cannot stop v6d: v6d is not running."
		failure $"cannot stop v6d: v6d is not running."
		echo
		return 1;
	fi

	killproc v6d
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f ${SUBSYS_FILE}
	return $RETVAL
}

restart() {
	stop
	start
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	*)
		echo $"Usage: $0 {start|stop|restart}"
		exit 1
esac
