#!/sbin/openrc-run
# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-x86/app-emulation/xen-tools/files/xend.initd-r2,v 1.2 2011/09/10 17:22:46 alexxy Exp $

depend() {
	need xenconsoled xenstored
	after firewall
	before xendomains sshd
}

await_daemons_up() {
	local i=1 rets=10
	while [ $i -lt $rets ]; do
		/usr/sbin/xend status && return 0
		sleep 1
	done
	return 1
}

is_privileged_domain() {
	grep -qsE '^control_d$' /proc/xen/capabilities
	return $?
}

start() {
	if ! is_privileged_domain ; then
		eerror "Can't start xend - this is not a privileged domain."
		return 1
	fi

	ebegin "Starting Xen control daemon"
	/usr/sbin/xend start
	/usr/sbin/xend status || await_daemons_up
	eend $?
}

stop() {
	if [ "$(xm list | wc -l)" -gt 2 ]; then
		ebegin "  Stopping all domains"
		/usr/sbin/xl shutdown -a -w >/dev/null
		eend $?
	fi

	ebegin "Stopping Xen control daemon"
	/usr/sbin/xend stop
	eend $?
}

status() {
	is_privileged_domain && /usr/sbin/xend status
}
