#!/bin/bash
#
# xencommons	Script to start and stop xenstored and xenconsoled
#	               FOR USE WITH LIBXL, not xend
#
# Author:       Ian Jackson <ian.jackson@eu.citrix.com>
#
# chkconfig: 2345 70 10
# description: Starts and stops the Xen control daemon.
### BEGIN INIT INFO
# Provides:          xenstored xenconsoled
# Required-Start:    $syslog $remote_fs
# Should-Start:
# Required-Stop:     $syslog $remote_fs
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Default-Enabled:   yes
# Short-Description: Start/stop xenstored and xenconsoled
# Description:       Starts and stops the daemons neeeded for xl/libxenlight
### END INIT INFO

XENCONSOLED_PIDFILE=/var/run/xenconsoled.pid

shopt -s extglob
test -f /etc/sysconfig/xend && . /etc/sysconfig/xend

if   test "x$1" = xstart && \
     test -d /proc/xen && \
   ! test -d /proc/xen/capabilities && \
     grep '	xenfs$' /proc/filesystems >/dev/null && \
   ! grep '^xenfs ' /proc/mounts >/dev/null;
then
	mount -t xenfs xenfs /proc/xen
fi

if ! grep -q "control_d" /proc/xen/capabilities ; then
	exit 0
fi

do_start () {
	test -z "$XENSTORED_ROOTDIR" || export XENSTORED_ROOTDIR
	[[ "$XENSTORED_TRACE" == @(yes|on|1) ]] && export XENSTORED_TRACE
	xenstore-read -s / >/dev/null 2>&1 || xenstored

	test -z "$XENCONSOLED_TRACE" || XENCONSOLED_ARGS=" --log=$XENCONSOLED_TRACE"
	xenconsoled --pid-file=$XENCONSOLED_PIDFILE $XENCONSOLED_ARGS $XENCONSOLED_OPTIONS
}
do_stop () {
	if read 2>/dev/null <$XENCONSOLED_PIDFILE pid; then
		kill $pid
		while kill -9 $pid >/dev/null 2>&1; do sleep 0.1; done
		rm -f $XENCONSOLED_PIDFILE
	fi
}

case "$1" in
  start)
	do_start
	;;
  status)
        xenstore-read -s /
	;;
  stop)
	do_stop
	;;
  reload)
	echo >&2 'Reload not available; use force-reload'; exit 1
	;;
  force-reload|restart)
        do_stop
	do_start
	;;
  *)
	# do not advertise unreasonable commands that there is no reason
	# to use with this device
	echo $"Usage: $0 {start|stop|status|restart|force-reload}"
	exit 1
esac

exit $?
