#!/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

. /usr/share/lxc/lxc.functions

_LXC_DIRECTORY="${lxc_path}"

_OPTIONS="$(getopt -o P: -l lxcpath: -- "${@}")"

if [ "${?}" -ne 0 ]
then
	echo "Usage: $(basename ${0}) [-P|--lxcpath DIRECTORY]" >&2
	exit 1
fi

eval set -- "${_OPTIONS}"

while true
do
	case "${1}" in
	        -P|--lxcpath)
			_LXC_DIRECTORY="${2}"
			shift 2
			;;

		--)
			shift
			break
			;;

		*)
			echo "E: $(basename ${0}): internal error ${0}" >&2
			exit 1
			;;
	esac
done

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

for _STATUS in RUNNING FROZEN STOPPED
do
	echo ${_STATUS}

	for _CONTAINER in $(lxc-ls -P "${_LXC_DIRECTORY}")
	do
		if lxc-info -n ${_CONTAINER} -P "${_LXC_DIRECTORY}" 2>&1 | grep -qs "${_STATUS}"
		then
			printf "  %-55.50s" "${_CONTAINER}"

			if [ -e /etc/lxc/auto/${_CONTAINER} ]
			then
				printf "%-10.6s" "(auto)"
			else
				printf "%-10.6s" "      "
			fi

			case "${_STATUS}" in
				RUNNING)
					if ps -eaf | grep -sq "lxc-console --name ${_CONTAINER}\$"
					then
						printf "%-10.9s" "[CONSOLE]"
					fi
					;;
			esac

			printf "\n"
		fi
	done

	echo
done
