#!/bin/sh
# chkconfig: 345 98 02
# description: The vservers service is used to start and stop all
#              the virtual servers.
#
# $Id: vservers-legacy.init,v 1.4 2008-04-29 20:45:28 glen Exp $

. /etc/init.d/functions

. /etc/sysconfig/vservers-legacy

[ -n "$UTIL_VSERVER_VARS" ] || UTIL_VSERVER_VARS=/usr/lib64/util-vserver/util-vserver-vars
if [ ! -e "$UTIL_VSERVER_VARS" ] ; then
	echo "Can not find util-vserver installation (the file '$UTIL_VSERVER_VARS' would be expected); aborting..." >&2
	exit 1
fi
. "$UTIL_VSERVER_VARS"

# Print the vserver name in priority/alpha order
sortserver(){
	(
	cd $__CONFDIR
	for serv in *.conf; do
        test -f "$serv" || continue

		PRIORITY=100
		. $serv
		test "$ONBOOT" || continue
		printf "%03d %s\n" $PRIORITY $(basename $serv .conf)
	done
	) | sort $* | (while read a b; do echo $b; done)
}

startservers(){
	cd $__CONFDIR
	for name in $(sortserver); do
		ONBOOT=
		. $name.conf
		if [ "$ONBOOT" = "yes" ] ; then
			$_VSERVER_LEGACY $name start
		fi
	done
}

start() {
  	if [ ! -f /var/lock/subsys/vservers-legacy ] ; then
	    show "Starting the virtual servers"
	    busy
	    if [ "$BACKGROUND" = "yes" ] ; then
			startservers >/dev/tty8 </dev/tty8 2>/dev/tty8 &
	    else
			startservers
	    fi
	    touch /var/lock/subsys/vservers-legacy
	    ok
	else
	    msg_already_running "virtual servers"
	fi
}

stop() {
  	if [ -f /var/lock/subsys/vservers-legacy ] ; then
	    show "Stopping the virtual servers"
	    busy
	    cd $__CONFDIR
	    for name in $(sortserver -r); do
			$_VSERVER_LEGACY $name stop
	    done
	    rm -f /var/lock/subsys/vservers-legacy
	    ok
	else
	    msg_not_running "virtual servers"
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	stop
	start
	;;
  status)
  	if [ -f /var/lock/subsys/vservers-legacy ]; then
	    cd $__CONFDIR
	    for serv in *.conf; do
			ONBOOT=no
			name=$(basename $serv .conf)
			. $serv
			echo -n ONBOOT=$ONBOOT " "
			$_VSERVER_LEGACY $name running
	    done
	else
	    msg_not_running "virtual servers"
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|status}"
	exit 3
esac

exit $RETVAL
