#!/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: virt-shutdown
# Should-Start: libvirtd
# Default-Start: 3 4 5
# Short-Description: shutdown libvirt domains
# Description: This is a script for shutting down virtual machines
#              on shutdown of host system.
### END INIT INFO

# the following is chkconfig init header
#
# virt-shutdown:   shutdown libvirt domains
#
# chkconfig: 345 97 01
# description:  This is a scripts for shutting down virtual machines
#               on shutdown of host system.
#

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

LC_ALL=C
VIRSH="virsh -c qemu:///system"
WAIT_SECONDS=300
post_script() {
  true
}

RETVAL=0

[ -e /etc/sysconfig/virt-shutdown ] && . /etc/sysconfig/virt-shutdown

stop() {
    echo -n $"Shutting down virtual machines: "

    # save
    for DOM_ID in $SAVE; do
      echo "Saving domain $DOM_ID"
      $VIRSH managedsave --bypass-cache --verbose $DOM_ID
    done
    
    # shutdown
    DOM_LIST=`$VIRSH list | grep running | awk '{ print $1 }'`
    for DOM_ID in $DOM_LIST; do
      echo -n "`$VIRSH domname $DOM_ID | head -n 1` "
      $VIRSH shutdown $DOM_ID >/dev/null
    done

    N=`$VIRSH list | grep running | wc -l`
    WAIT_SECONDS=$((WAIT_SECONDS*N))
    for i in `seq $WAIT_SECONDS`; do
      N=`$VIRSH list | grep running | wc -l`
      if [ $N -eq 0 ]; then
        break
      fi
      sleep 1
      echo -n "$N "
    done

    if [ $N -eq 0 ]; then
      RETVAL=0
      echo
    else
      echo
      echo "These virtual machines are still running:"
      $VIRSH list | grep running
      RETVAL=1
    fi
    post_script stop
}

# See how we were called.
case "$1" in
    start)
    	touch /var/lock/subsys/virt-shutdown
    	RETVAL=0
    	;;
    stop)
        stop
        rm -f /var/lock/subsys/virt-shutdown
        ;;
    status)
    	status virt-shutdown
        $VIRSH list
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|status}"
	exit 1
        ;;
esac
exit $RETVAL
