#!/bin/sh
#
# /etc/init.d/xendomains
# Start / stop domains automatically when domain 0 boots / shuts down.
#
# chkconfig: 345 99 00
# description: Start / stop Xen domains.
#
# This script offers fairly basic functionality.
#
# Based on the example in the "Designing High Quality Integrated Linux
# Applications HOWTO" by Avi Alkalay
# <http://www.tldp.org/HOWTO/HighQuality-Apps-HOWTO/>
#

RETVAL=0

INITD=/etc/init.d/
. $INITD/functions

on_fn_exit()
{
    if [ $RETVAL -eq 0 ]; then
	success
    else
	failure
    fi
    
    echo
}

start() {
    if [ -f /var/lock/subsys/xendomains ]; then return; fi

    echo -n $"Starting auto Xen domains:"

    # we expect config scripts for auto starting domains to be in
    # /etc/xc/auto/ - they could just be symlinks to files elsewhere
    if [ $(ls /etc/xc/auto/ | wc -l) -gt 0 ]; then
	
       # create all domains with config files in /etc/xc/auto
	for dom in /etc/xc/auto/*; do
	    xc_dom_create.py -q -f $dom
	    if [ $? -ne 0 ]; then
		RETVAL=$?
	    fi
	done
    fi

    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/xendomains

    on_fn_exit
}

stop()
{
    # NB. this shuts down ALL Xen domains (politely), not just the ones in
    # /etc/xc/auto/*
    # This is because it's easier to do ;-) but arguably if this script is run
    # on system shutdown then it's also the right thing to do.
    
    echo -n $"Shutting down all Xen domains:"

    if [ $(ls /var/run/xendomains/ | wc -l) -gt 0 ]; then
	
	cd /var/run/xendomains/

	for pid in *; do
	   
	    kill -s SIGTERM $(cat $pid)

	done

    fi

    sleep 3 # avoid races

    xc_dom_control.py shutdown all -w # shut down all domains, politely and wait
                                      # for all to exit
    
    RETVAL=$?

    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/xendomains

    on_fn_exit
}

# This does NOT necessarily restart all running domains: instead it
# stops all running domains and then boots all the domains specified in
# /etc/xc/auto.  If other domains have been started manually then they will
# not get restarted.
# Commented out to avoid confusion!
#
#restart()
#{
#    stop
#    start
#}

# same as restart for now - commented out to avoid confusion
#reload()
#{
#    restart
#}


case "$1" in
    start)
	start
	;;

    stop)
	stop
	;;

# The following are commented out to disable them by default to avoid confusion
# - see the notes above
#
#    restart)
#	restart
#	;;
#
#    reload)
#	reload
#	;;

    status)
	xc_dom_control.py list
	;;

    *)
	echo $"Usage: $0 {start|stop|status}"
	;;
esac

exit $RETVAL
