#!/bin/sh -

LXC_HOME=/srv/lxc
LXC_VAR=/var/lib/lxc
CGROUP_MOUNT=/var/lib/group

if test -f /etc/lxc/lxc.conf
then
	. /etc/lxc/lxc.conf
fi

function get_cgroup()
{
	local CGROUP_STRING
	CGROUP_STRING=$(mount -t cgroup |grep -E -e '^lxc ')
	if test -z "$mount_string"; then
		CGROUP_STRING=$(mount |grep -m1 'type cgroup')
	fi
	if test -n "$CGROUP_STRING"; then
		CGROUP_MOUNT=$(echo $CGROUP_MOUNT |cut -d' ' -f3)
	fi
}

get_rootfs() {
	local VM
	local CFG_ROOTFS
	local CFG_FSTAB

	VM=$1

	if test -f ${LXC_VAR}/${VM}/config
	then
		# Should the spaces in the next regexes be generic ws?
		CFG_ROOTFS=`sed -e '/lxc.rootfs *= */!d' -e 's/.*= *//' -e q \
			< ${LXC_VAR}/${VM}/config`
		CFG_FSTAB=`sed -e '/lxc.mount *= */!d' -e 's/.*= *//' -e q \
			< ${LXC_VAR}/${VM}/config`

		# Assume
		ROOTFS=$CFG_ROOTFS

		# if the rootfs is specified in the fstab, dereference back
		# to the original source.  Making this work with unionfs
		# or any fuse fs is going to be a major RPITA.  But they
		# don't work, yet, ANYWAYS.
		if test -n "$CFG_FSTAB"
		then
			ROOT_MOUNT=`grep " $CFG_ROOTFS " $CFG_FSTAB`
			if test -n "$ROOT_MOUNT"
			then
				ROOT_MOUNT=`expr "$ROOT_MOUNT" : '\([^ ]*\)'`
				if test -n "$ROOT_MOUNT" -a -d "$ROOT_MOUNT"
				then
					ROOTFS=$ROOT_MOUNT
				fi
			fi
		fi
	fi
}


VM=$1

ECHO=": echo"
ECHO="echo"

# We use to be able to use lxc-ls but it now prints active VM's twice
for VM in `ls $LXC_VAR`
do
	STATE=`lxc-info -n ${VM} | sed -e 's/.* is //'`

	if test "$STATE" = "RUNNING"
	then
		UTSNAME=`sed -e '/^lxc.utsname/!d' -e 's/.*= *//' < /var/lib/lxc/${VM}/config`
		PROCS=`cat ${CGROUP_MOUNT}/${VM}/tasks | wc -l`

		get_rootfs ${VM}

		${ECHO} "Checking $VM $ROOTFS $UTSNAME ($PROCS)"

		# Do we need to check for other locations for utmp?
		if test "$PROCS" = 1 -a -f ${ROOTFS}/var/run/utmp
		then
			RUNLEVEL=`runlevel ${ROOTFS}/var/run/utmp`
			if test "$RUNLEVEL" = "unknown"
			then
				# Damn Debian and Ubuntu for putting tmpfs on /var/run
				RUNLEVEL=`runlevel ${ROOTFS}/var/log/wtmp`
			fi
			${ECHO} "Runlevel $VM $UTSNAME ($RUNLEVEL)"
			case $RUNLEVEL in
			N*)
			# Don't do anything if he's in a new boot state
				;;

			??0)
			# He's halted...  Kill the VM.
				echo "Halting ${VM} ${UTSNAME}"
				lxc-stop -n ${VM}
				;;

			??6)
			# He's rebooting...  Kill the VM and start again...
				echo "Rebooting ${VM} ${UTSNAME}"
				lxc-stop -n ${VM}
				lxc-wait -n ${VM} -s STOPPED
				STAMP=`date +%F-%T`
				lxc-start -d -o ${LXC_HOME}/logs/${VM}.${STAMP}.log -n ${VM}
				;;

			*)
			# Ignore everything else.
			# Should never get to this state...
				;;
			esac
		fi
	fi
done
