#!/bin/sh

## Copyright (C) 2006-2013 Daniel Baumann <mail@daniel-baumann.ch>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

_PROGRAM="${1}"

if [ -n "${_PROGRAM}" ]
then
	shift
else
	echo "Usage: ${0} PROGRAM CONTAINER"
	exit 1
fi

if [ ! -x "$(which lxc-${_PROGRAM} 2>/dev/null)" ]
then
	echo "E: lxc-${_PROGRAM} - no such program" >&2
	exit 1
fi

_CONTAINER="${1}"

case "${_PROGRAM}" in
	checkconfig|list|ls|setcap|setuid|version)
		# programs do not require any container as argument

		;;

	*)
		if [ -n "${_CONTAINER}" ]
		then
			shift

			case "${_PROGRAM}" in
				clone|create|monitor|wait)
					# programms do not require an existing container as argument

					;;

				*)
					if ! lxc-ls | grep -qs ^${_CONTAINER}$
					then
						echo "E: ${_CONTAINER} - no such container" >&2
						exit 1
					fi
					;;
			esac

			_OPTIONS="--name ${_CONTAINER}"
		else
			echo "Usage: ${0} PROGRAM CONTAINER"
			exit 1
		fi
		;;
esac

lxc-${_PROGRAM} ${_OPTIONS} ${@}
