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

Lxc ()
{
	_PROGRAM="${1}"
	shift

	_OPTIONS="${@}"

	# no containers available
	if ! ls /etc/lxc/auto/* > /dev/null 2>&1
	then
		exit 0
	fi

	for _CONFIG in /etc/lxc/auto/*
	do
		if [ -L "${_CONFIG}" ] && [ ! -e "${_CONFIG}" ]
		then
			# dangling symlink
			continue
		fi

		_CONTAINER="$(basename $(dirname $(readlink -e ${_CONFIG})))"

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

					lxc-start -n ${_CONTAINER} -f ${_CONFIG} -d ${_OPTIONS}
				fi
				;;

			*)
				log_progress_msg "${_CONTAINER}"

				lxc-${_PROGRAM} -n ${_CONTAINER} ${_OPTIONS}
				;;
		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 -t 10
		;;

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

		Lxc stop
		Lxc start
		;;

	freeze)
		log_daemon_msg "Freezing Linux Containers"

		Lxc freeze
		;;

	unfreeze)
		log_daemon_msg "Unfreezing Linux Containers"

		Lxc unfreeze
		;;

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

exit 0
