#!/bin/bash
# Copyright 2005 The vserver-utils Developers
# See AUTHORS for details
#
# 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.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

: ${VU_PATHCONFIG:=/usr/share/vserver-utils/pathconfig}

if [ ! -e "${VU_PATHCONFIG}" ]; then
	echo "Cannot find vserver-utils installation!" >&2
	echo "The file '${VU_PATHCONFIG}' would be expected" >&2
	exit 1
fi

source ${VU_PATHCONFIG}

[ -z "${_HAVE_LIB_UTIL}" ] && source ${_LIB_UTIL}


# Supported commands
n=0
for i in ${__PKGDATACOMMANDSDIR}/*; do
	COMMANDS[n++]=$(basename ${i/.sh})
done


usage() {
	echo "Usage: vserver <command> [<localopts>]"
	echo
	echo "  <command>     See supported commands below"
	echo "  <localopts>   Command specific options"
	echo
	echo "Supported commands:"
	for i in ${COMMANDS[@]}; do
		echo "    ${i}"
	done
	echo
	echo "Type vserver <command> --help for details"
}

# Save the commandline (some library functions need this)
CMDORIG="$0 $@"

# 1. Check for "vserver <command> --help" construct
if [ "$2" == "--help" ]; then
	for i in ${COMMANDS[@]}; do
		if [ "$i" == "$1" ]; then
			source ${__PKGDATACOMMANDSDIR}/${i}.sh
			${i}.usage
			exit 0
		fi
	done
	
	util.error "Selected command not supported"
fi


# 2. Check for "vserver --help" construct
if [ "$1" == "--help" ]; then
	usage
	exit 0
fi


# 3. Check <command>
[ -z "$1" ] && util.error "Missing required argument <command>"

for i in ${COMMANDS[@]}; do
	[ "${i}" == "$1" ] && command=$1 && shift
done

[ -z "${command}" ] && util.error "Selected command not supported"


# 4. Start command
source ${__PKGDATACOMMANDSDIR}/${command}.sh

set -e
trap "${command}.interrupt_handler" INT
trap "${command}.exit_handler" EXIT

${command}.main "$@"
