#!/bin/bash
#
# vdispatch-conf - Update config files inside vservers
# Copyright (C) 2005 Benedikt Boehm <hollow@gentoo.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
#
# v0.1 - initial release

trap "exit 1" INT

if [ -r /sbin/functions.sh ]; then
	source /sbin/functions.sh
else
	echo "/sbin/functions.sh missing. Are you running Gentoo?"
fi

die() {
# $1 - error message
# $2 - exit code
	eerror ${1:-<no error message>}
	einfo "Type ${APP} --help for details"
	
	exit ${2:-1}
}

dispatchconf() {
# $1 - name of the vserver
	einfo "Updating config files for '${1}'"
	/usr/sbin/vserver ${1} exec /usr/sbin/dispatch-conf
	echo
	
}

usage() {
	echo "Usage: vupdateworld <opts> [<name>]"
	echo
	echo "<name>       Name of the vserver (required if --all not used)"
	echo
	echo "Options:"
	echo " -h, --help                 This help message"
	echo " -a, --all                  Update all running vservers"
	echo
}

# Parsing opts
opts=$(POSIXLY_CORRECT=1 getopt -o ha --longoptions help,all -n $0 -- "$@")

[ "$?" != "0" ] && die "Wrong number of options"

eval set -- "$opts"

all=0

while true; do
	case "${1}" in
		--help|-h)
			usage
			exit 0
			;;
		--all|-a)
			all=1
			shift
			;;
		*)
			die "Unknown argument '${1}'"
			;;
	esac
done

# checking vserver name
name=
if [ -z "$1" ] && [ ${all} -eq 0 ]; then
	die "Missing argument <name>"
else
	name=$1
fi
shift

# get the list of vservers
if [ ${all} -eq 0 ] ; then
	vservers=${name}
else
	running="$(find /proc/virtual/ -mindepth 1 -maxdepth 1 -type d)"
	for xid in ${running} ; do
		vservers="${vservers} $(/usr/sbin/vserver-stat | /bin/grep "^${xid##*/}" | /bin/awk '{ print $8 }')"
	done
fi

# finally, update configs
for vserver in ${vservers} ; do
	dispatchconf ${vserver}
done
