#!/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|all [OPTIONS]"
	exit 1
fi

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

_CONTAINERS="${1}"

if [ -n "${_CONTAINERS}" ]
then
	shift

	case "${_CONTAINERS}" in
		all)
			_CONTAINERS="$(lxc-ls)"
			;;
	esac
fi

_OPTIONS="${@}"

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

	*)
		if [ -z "${_CONTAINERS}" ]
		then
			echo "Usage: ${0} PROGRAM CONTAINER|all [OPTIONS]"
			exit 1
		fi

		for _CONTAINER in ${_CONTAINERS}
		do
			case "${_PROGRAM}" in
				clone|create|monitor|wait)
					# programms do not require an existing container as argument
					_NAME=""
					;;

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

					_NAME="--name ${_CONTAINER}"
					;;
			esac

			lxc-${_PROGRAM} ${_NAME} ${_OPTIONS}
		done
		;;
esac
