#!/bin/sh

# the following is the LSB init header see
# http://www.linux-foundation.org/spec//booksets/LSB-Core-generic/LSB-Core-generic.html#INITSCRCOMCONV
#
### BEGIN INIT INFO
# Provides:          libvirtd
# Should-Start:      xend
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: daemon for libvirt virtualization API
# Description:       This is a daemon for managing QEMU guest instances
#                    and libvirt virtual networks
#                    See http://libvirt.org/
### END INIT INFO

. /etc/rc.status
rc_reset

LIBVIRTD_BIN=/usr/sbin/libvirtd

libvirtd_abort()
{
        echo -n "libvirtd "
        rc_failed $1
        rc_status -v
        rc_exit
}

check()
{
        if [ "$1" == status ]; then
                if [ ! -e /proc/xen/capabilities ]; then
                        libvirtd_abort 3
                fi
        else
                if [ `id -u` != 0 ]; then
                        libvirtd_abort 4
                fi
                if [ ! -e /proc/xen/capabilities ] ||
                     ! grep control_d /proc/xen/capabilities >/dev/null 2>&1; then
                        if [ "$1" == stop ]; then
                                libvirtd_abort 0
                        else
                                libvirtd_abort 6
                        fi
                fi
        fi
}

case "$1" in
    start)
	check $1
        echo -n "Starting libvirtd "
        startproc $LIBVIRTD_BIN -d -l
        rc_status -v
        ;;
    stop)
	check $1
        echo -n "Shutting down libvirtd "
        killproc -TERM $LIBVIRTD_BIN > /dev/null 2>&1
        rc_status -v
        ;;
    try-restart)
	check $1
        $0 status >/dev/null &&  $0 restart
        rc_status
        ;;
    restart)
	check $1
        $0 stop
        $0 start
        rc_status
        ;;
    reload)
	check $1
	killproc -HUP $LIBVIRTD_BIN
        rc_status -v
        ;;
    status)
	check $1
        echo -n "Checking status of libvirtd "
        checkproc $LIBVIRTD_BIN
        rc_status -v
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|try-restart|reload|status}"
	rc_failed 2
	rc_exit
        ;;
esac
rc_exit
