#!/bin/bash
#
# xend		Starts and stops the Xen control daemon
#
# chkconfig: 35 98 01
# description: Starts and stops the Xen control daemon
#
### BEGIN INIT INFO
# Provides:          xend
# Required-Start:    $syslog
# Should-Start:      $time $network $remote_fs
# Required-Stop:     $syslog
# Should-Stop:       $time $network $remote_fs
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: Starts and stops the Xen control daemon
# Description:       Starts and stops the Xen control daemon.  xend is needed
#                    to use Xen.
### END INIT INFO

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_abort()
{
	echo -n "xend "
	rc_failed $1
	rc_status -v
	rc_exit
}

if [ "$1" == status ]; then
	if [ ! -e /proc/xen/capabilities ]; then
		xend_abort 3
	fi
else
	if [ `id -u` != 0 ]; then
		xend_abort 4
	fi
	if [ ! -e /proc/xen/capabilities ] ||
	     ! grep control_d /proc/xen/capabilities >/dev/null 2>&1; then
		if [ "$1" == stop ] ||
		   [ "$1" == try-restart ]; then
			xend_abort 0
		else
			xend_abort 6
		fi
	fi
fi

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

#export PYTHONOPTIMIZE=2
case "$1" in
  start)
	echo -n "Starting xend "
	if [ ! -z "$XEND" ]; then
		echo -n "(already running pid $XEND) "
	fi
	# Load XEN backend modules
	# Sidenote: They could be loaded later:
	# - netloop at network-bridge init time
	# - netbk and blkbk when the dom0 hotplug events occur
	#   (in xen-network-common.sh and block-common.sh)
	# but for now it's safest to have them loaded when xend starts in dom0.
	modprobe netloop 2>/dev/null || true
	modprobe netbk 2>/dev/null || true
	modprobe blkbk 2>/dev/null || true
	xend start
	await_daemons_up
	;;
  stop)
	echo -n "Stopping xend "
	if [ -z "$XEND" ]; then
		echo -n "(not running) "
		xend stop
		rc_reset
	else
		echo -n "(pid $XEND) "
		unset sysrq_sent
		while read nm id mem vcpu state time; do
			if [ $id = 0 ]; then continue; fi
			sysrq_sent=1
			echo -en "\n Warning: Domain $nm (ID $id) still up ($state)"
			# Domains should be closed down by xendomains; anyway, send
			# SysRq-S to avoid the worst in case domains are not shut down.
			xm sysrq $id s
		done < <(xm list | grep -v ^Name)
		if [ -n "$sysrq_sent" ]; then sleep 1; fi
		xend stop
		rc_reset
	fi
	;;
  status)
	echo -n "Checking status of xend "
	if [ ! -z "$XEND" ]; then
		echo -n "(pid $XEND) "
	fi
	xend status
	;;
  restart|reload)
	echo -n "Restarting xend "
	if [ -z "$XEND" ]; then
		echo -n "(not running) "
	else
		echo -n "(old pid $XEND) "
	fi
	xend restart
	await_daemons_up
	;;
  try-restart)
	$0 status
	if [ $? = 0 ]; then
		$0 restart
	else
		rc_reset
	fi
	;;
  *)
	echo "Usage: $0 {start|stop|restart|try-restart|reload|status}"
	rc_failed 2
	rc_exit
esac

#unset PYTHONOPTIMIZE
rc_status -v
rc_exit
