#!/bin/sh

### BEGIN INIT INFO
# Provides:		lxc
# Required-Start:	$syslog $remote_fs
# Required-Stop:	$syslog $remote_fs
# Should-Start:
# Should-Stop:
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Linux Containers
# Description:		Linux Containers
# X-Start-Before:
# X-Stop-After:
# X-Interactive:	true
### END INIT INFO

if [ ! -x /usr/bin/lxc ]
then
	exit 0
fi

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

. /lib/lsb/init-functions

if [ -f /etc/default/lxc ]
then
	. /etc/default/lxc
fi

LXC_AUTO="${LXC_AUTO:-true}"

Lxc ()
{
	_PROGRAM="${@}"

	# no containers available
	if ! ls /etc/lxc/auto/* > /dev/null 2>&1
	then
		log_progress_msg "(none)"
		log_end_msg 0

		exit 0
	fi

	for _CONFIG in /etc/lxc/auto/*
	do
		_CONTAINER="$(basename $(dirname $(readlink -e ${_CONFIG})))"

		if [ -L "${_CONFIG}" ] && [ ! -e "${_CONFIG}" ]
		then
			# dangling symlink
			log_progress_msg "${_CONTAINER} (broken)"

			continue
		fi

		case "${_PROGRAM}" in
			start)
				# initscript is disabled
				case "${LXC_AUTO}" in
					false)
						log_progress_msg "(disabled)"
						log_end_msg 0

						exit 0
						;;
				esac

				if ! lxc-info -n ${_CONTAINER} 2>&1 | grep -qs "RUNNING"
				then
					log_progress_msg "${_CONTAINER}"

					lxc-start -n ${_CONTAINER} -f ${_CONFIG} -d
				else
					log_progress_msg "${_CONTAINER} (skip)"
				fi
				;;

			*)
				log_progress_msg "${_CONTAINER}"

				lxc ${_PROGRAM} ${_CONTAINER}
				;;
		esac
	done

	log_end_msg 0
}

case "${1}" in
	start)
		log_daemon_msg "Starting Linux Containers"

		Lxc start
		;;

	stop)
		log_daemon_msg "Stopping Linux Containers"

		Lxc shutdown
		;;

	restart|force-reload)
		log_daemon_msg "Restarting Linux Containers"

		Lxc shutdown
		Lxc start
		;;

	freeze)
		log_daemon_msg "Freezing Linux Containers"

		Lxc freeze
		;;

	unfreeze)
		log_daemon_msg "Unfreezing Linux Containers"

		Lxc unfreeze
		;;

	status)
		lxc-list
		;;

	*)
		log_success_msg "Usage: ${0} {start|stop|restart|force-reload|freeze|unfreeze|status}"
		exit 1
		;;
esac

exit 0
