#!/bin/sh
# /etc/init.d/lxc
#   and its symbolic link
# /usr/sbin/rclxc
#
# System startup script for LXC containers.
# For lxc 0.7.2 which doesn't require an external monitor process to perform
# the lxc-stop when a containers init process requests init 0|1|6 .
#
# 20101108 - Brian K. White - brian@aljex.com
#
### BEGIN INIT INFO
# Provides:          lxc
# Required-Start:    $ALL
# Should-Start:
# Required-Stop:     $ALL
# Should-Stop:
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: LXC Linux Containers
# Description:       Start/Stop LXC containers.

### END INIT INFO

. /etc/rc.status

LXC_ETC=/etc/lxc
LXC_SRV=/srv/lxc
CGROUP_MOUNT_POINT=/var/run/lxc/cgroup
CGROUP_MOUNT_NAME=lxc
CGROUP_MOUNTED=false
CGROUP_RELEASE_AGENT="/usr/sbin/lxc_cgroup_release_agent"
LXC_CONF=${LXC_ETC}/lxc.conf
[[ -s $LXC_CONF ]] && . $LXC_CONF

# Various possible overrides to cgroup mount point.
# If kernel supplies cgroup mount point, prefer it.
[[ -d /sys/fs/cgroup ]] && CGROUP_MOUNT_POINT=/sys/fs/cgroup CGROUP_MOUNT_NAME=cgroup
# If cgroup already mounted, use it no matter where it is.
# If multiple cgroup mounts, prefer the one named lxc if any.
eval `awk 'BEGIN{P="";N=""}END{print("cgmp="P" cgmn="N)}($3=="cgroup"){N=$1;P=$2;if($1="lxc")exit}' /proc/mounts`
[[ "$cgmn" && "$cgmp" && -d "$cgmp" ]] && CGROUP_MOUNT_POINT=$cgmp CGROUP_MOUNT_NAME=$cgmn CGROUP_MOUNTED=true

lxcstrt () {
	$CGROUP_MOUNTED || {
		[[ -d $CGROUP_MOUNT_POINT ]] || mkdir -p $CGROUP_MOUNT_POINT
		mount -t cgroup $CGROUP_MOUNT_NAME $CGROUP_MOUNT_POINT
	}
	echo "$CGROUP_RELEASE_AGENT" >${CGROUP_MOUNT_POINT}/release_agent
	echo 1 >${CGROUP_MOUNT_POINT}/notify_on_release
	cd $LXC_ETC
	for CF in */config ; do
		CN=${CF%/*}
		[[ "${1:-$CN}" = "$CN" ]] || continue
		screen -dmS $CN lxc-start -f $CF -n $CN
	done
}

lxcstop () {
	typeset -i PID=0
	lxc-ps -C init -opid |while read CN PID ;do
		[[ $PID -gt 1 ]] || continue
		[[ "${1:-$CN}" = "$CN" ]] || continue
		grep -q 'p0::powerfail:/sbin/init 0' ${LXC_SRV}/${CN}/etc/inittab || continue
		kill -PWR $PID
	done
}

lxcstat () {
	typeset -i R=0
	cd $LXC_ETC
	for CF in */config ; do
		CN="${CF%/*}"
		[[ "${1:-$CN}" = "$CN" ]] || continue
		S=`lxc-info -n $CN`
		echo "$S"
		[[ "${S##* }" = "RUNNING" ]] && ((R++))
	done
	[[ $R -gt 0 ]] && return 0 || return 3
}

rc_reset

case "$1" in
	start)
		echo -n "Starting LXC containers..."
		lxcstrt $2
		rc_status -v
		;;
	stop)
		echo -n "Shutting down LXC containers..."
		lxcstop $2
		while $0 status $2 >/dev/null 2>&1 ; do sleep 2 ; done
		rc_status -v
		;;
	try-restart)
		$0 status && $0 restart || rc_reset
		rc_status
		;;
	restart)
		$0 stop $2
		$0 start $2
		rc_status
		;;
	status)
		echo -n "Checking for LXC containers..."
		lxcstat $2 >/dev/null 2>&1
		rc_status -v
		;;
	info|list|show)
		echo "Listing LXC containers..."
		lxcstat $2
		;;
	*)
		echo "Usage: $0 {start|stop|try-restart|restart|status|list} [container_name]"
		exit 1
		;;
esac

rc_exit
