#!/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.

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

RETVAL=0


[ `id -u` = 0 ] || exit 4

# Avoid error when running under non-Xen kernel
if [ ! -d /proc/xen ]; then
	exit 0
fi
if ! grep -q "control_d" /proc/xen/capabilities ; then
	exit 0
fi

prog=xend

XENSTORED_TMPFS=yes
XENCONSOLED_LOG_HYPERVISOR=no
XENCONSOLED_LOG_GUESTS=no
XENCONSOLED_TIMESTAMP_HYPERVISOR_LOG=no
XENCONSOLED_TIMESTAMP_GUEST_LOG=no
XENCONSOLED_LOG_DIR=/var/log/xen/console

test -f /etc/sysconfig/xend && . /etc/sysconfig/xend

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

case "$1" in
  start)
	echo -n $"Starting $prog: "
	modprobe blkbk
	modprobe blktap
	modprobe netbk
	modprobe netloop
 
        export XENCONSOLED_LOG_DIR
        export XENCONSOLED_LOG_GUESTS
        export XENCONSOLED_LOG_HYPERVISOR
        export XENCONSOLED_TIMESTAMP_HYPERVISOR_LOG
        export XENCONSOLED_TIMESTAMP_GUEST_LOG

        if [ "$XENSTORED_TMPFS" = "yes" ]; then
            pid=
            test -f "/var/run/xenstore.pid" && ( read pid < "/var/run/xenstore.pid" )
            if [ -z "$pid" -o ! -d "/proc/$pid" ]; then
                grep '/var/lib/xenstored' /proc/mounts 1>/dev/null 2>&1
                test "$?" = "1" && (
			mount -t tmpfs none /var/lib/xenstored
			restorecon -R /var/lib/xenstored
		)
            fi
        fi

	/usr/sbin/xend start
	await_daemons_up
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
	;;
  stop)
	echo -n $"Stopping $prog: "
	/usr/sbin/xend stop
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
        RETVAL=$?
	;;
  status)
	/usr/sbin/xend status
	if [ $? = 0 ] ; then
	    echo xend is running
	    exit 0
	else
	    if [ -f /var/run/xend.pid ]; then
		echo xend appears to be dead but /var/run/xend.pid file exists
		exit 1
	    fi
	    if [ -f /var/lock/subsys/xend ]; then
		echo xend appears to be dead but /var/lock/subsys/xend file exists
		exit 2
	    fi
	    echo xend is stopped
	    exit 3
	fi
	;;
  restart|reload|force-reload)
        echo -n $"$1 $prog: "
	/usr/sbin/xend restart
	await_daemons_up
	;;
  *)
	# do not advertise unreasonable commands that there is no reason
	# to use with this device
	echo $"Usage: $0 {start|stop|status|restart|reload|force-reload}"
	exit 1
esac

if [ $RETVAL = 0 ] ; then
    echo_success
    echo
else
    echo_failure
    echo
fi
exit $RETVAL

