#!/bin/bash
#
# xend		Script to start and stop the Xen control daemon.
#
# Author:       Keir Fraser <keir.fraser@cl.cam.ac.uk>
#
# chkconfig: 2345 98 01
# description: Starts and stops the Xen control daemon.
#
### BEGIN INIT INFO
# Provides:          xend
# Required-Start:    $syslog $remote_fs
# Should-Start: $time ypbind nscd
# Required-Stop:     $syslog $remote_fs
# Should-Stop: $time ypbind nscd
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: Starts and stops the Xen control daemon.
# Description:       xend is needed to use xen ...
### END INIT INFO

# Wait for Xend / Xfrd to be up
function await_daemons_up
{
	i=1
	rets=10
	xend status
	while [ $? -ne 0 -a $i -lt $rets ]; do
	    sleep 1
	    echo -n .
	    i=$(($i + 1))
	    xend status
	done
}

. /etc/rc.status
rc_reset

XEND=`ps ax | grep xend | grep python | awk '{ print $1 }'`

case "$1" in
  start)
	echo -n "Starting xend "
	if test ! -z "$XEND"; then
		echo -n "(already running pid $XEND) "
	fi
	if test ! -d /proc/xen; then
		rc_failed 6
	elif test ! -e /proc/xen/privcmd; then
		rc_failed 4
	else
		xend start
		await_daemons_up
	fi
	rc_status -v
	;;
  stop)
	echo -n "Stopping xend "
	if test -z "$XEND"; then
		echo -n "(not running) "
		if test -d /proc/xen; then
			xend stop
		fi
	else 
		echo -n "(pid $XEND) "
		xend stop
	fi
	rc_status -v
	;;
  status)
	echo -n "Checking status of xend "
	if test ! -z "$XEND"; then
		echo -n "(pid $XEND) "
	fi
	xend status
	rc_status -v
	;;
  restart|reload)
	echo -n "Restarting xend "
	if test -z "$XEND"; then
		echo -n "(not running) "
	else
		echo -n "(old pid $XEND) "
	fi
	if test ! -d /proc/xen; then
		rc_failed 7
	else
		xend restart
		await_daemons_up
	fi
	rc_status -v
	;;
  *)
	# do not advertise unreasonable commands that there is no reason
	# to use with this device
	echo $"Usage: $0 {start|stop|status|restart|reload}"
	exit 1
esac

exit $?

