#!/bin/sh
# chkconfig: 345 98 02
# description: The vservers service is used to start and stop all
#              the virtual servers.

. /etc/init.d/functions

. /etc/sysconfig/vservers-legacy

[ -n "$UTIL_VSERVER_VARS" ] || UTIL_VSERVER_VARS=/usr/lib/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
}

# See how we were called.
case "$1" in
  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
	;;
  restart)
	$0 stop
	$0 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
	;;
  *)
	echo "Usage: vservers {start|stop|restart|status}"
	exit 1
esac

exit $RETVAL

# This must be last line !
# vi:syntax=sh:tw=78:ts=8:sw=4
