#!/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
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# 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


LIBVIRTD_BIN=/usr/sbin/libvirtd
test -x $LIBVIRTD_BIN || { echo "$LIBVIRD_BIN not installed";
         if [ "$1" = "stop" ]; then exit 0;
	 else exit 5; fi; }

. /etc/rc.status
rc_reset

# read configuration
[ -f /etc/sysconfig/libvirtd ] && . /etc/sysconfig/libvirtd

# type of hypervisor
hypervisor_type() {
	HYPERVISOR_KVM=`virsh version | grep "Running hypervisor" | grep QEMU | wc -l`
}

# number of running domains
libvirtd_domains() {
	DOM_COUNT=`virsh list | grep running | wc -l`
}


case "$1" in
    start)
        echo -n "Starting libvirtd "

        startproc $LIBVIRTD_BIN -d
        rc_status -v

        ;;
    stop)
        echo -n "Shutting down libvirtd "

	# try to shutdown all (KVM) domains
	libvirtd_domains # DOM_COUNT
	hypervisor_type # HYPERVISOR_KVM
	if [ $HYPERVISOR_KVM ] \
	    && [ "$LIBVIRTD_KVM_SHUTDOWN" = "yes" ] \
	    && [ "x$DOM_COUNT" != "x0" ]; then

		echo ""
		for VM in `virsh list | grep running | awk '{ print $1 }'`; do
			NAME="`virsh list|grep " ${VM} "|awk '{ print $2 }'`"
			echo -e "\tShutdown guest: ${NAME}"
			virsh shutdown $VM >/dev/null
		done

		if [ -n $LIBVIRTD_KVM_SHUTDOWN_MAXWAIT ] ; then
			COUNTER="${LIBVIRTD_KVM_SHUTDOWN_MAXWAIT}"
		else
			COUNTER=100
		fi

		DOT=0
		libvirtd_domains # DOM_COUNT
		while [ $DOM_COUNT -gt 0 ] && [ $COUNTER -gt 0 ] ; do
			libvirtd_domains # DOM_COUNT
			sleep 1
			COUNTER=$[$COUNTER-1]
			DOT=$[$DOT-1]
			if [ $DOT -le 0 ] ; then
				echo -n "."
				DOT=3
			fi
		done

		libvirtd_domains # DOM_COUNT
		if [ "x$DOM_COUNT" != "x0" ] ; then
			echo -n "some guests are still running - stopping nevertheless"
		fi
	fi

        killproc -TERM $LIBVIRTD_BIN > /dev/null 2>&1
        rc_status -v
        ;;
    try-restart)
        $0 status >/dev/null &&  $0 restart
        rc_status
        ;;
    restart)
        $0 stop
        $0 start
        rc_status
        ;;
    reload)
	killproc -HUP $LIBVIRTD_BIN
        rc_status -v
        ;;
    status)
        echo -n "Checking status of libvirtd "
        checkproc $LIBVIRTD_BIN
        rc_status -v
        ;;
    list)
	virsh list --all
	rc_failed 0
	rc_exit
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|try-restart|reload|status|list}"
	rc_failed 2
	rc_exit
        ;;
esac
rc_exit
