#!/bin/sh
#
# cgconfig	Control Groups Configuration Startup
# chkconfig:	2345 01 99
# description:	This script runs the cgconfigparser utility to parse and setup \
#		the control group filesystem. It uses /etc/cgconfig.conf \
#		and parses the configuration specified in there.

# Source function library
. /etc/rc.d/init.d/functions

# read the config
[ -f /etc/sysconfig/cgconfig ] && . /etc/sysconfig/cgconfig

mount_cgroup() {
	if [ -n "`grep /sys/fs/cgroup /proc/mounts`" ]; then
		return 0
	fi

	# kernel provides cgroups?
	if [ ! -e /proc/cgroups ]; then
		return 0
	fi

	run_cmd "Mounting /sys/fs/cgroup" mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup
}

umount_cgroup() {
	# If /sys/fs/cgroup is not mounted, we don't bother
	if [ -z "`grep /sys/fs/cgroup /proc/mounts`" ]; then
		return 0
	fi

	# Don't try to get too smart, just optimistically try to umount all
	# that we think we mounted
	run_cmd "Unmounting /sys/fs/cgroup" umount /sys/fs/cgroup
	return $?
}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/cgconfig ]; then
		msg_already_running "cgconfig"
		return
	fi
	if [ ! -s /etc/cgconfig.conf ]; then
		nls "/etc/cgconfig.conf is not configured"
		RETVAL=6
		return
	fi
	mount_cgroup
	msg_starting "cgconfig"; busy
	local out
	out=$(/sbin/cgconfigparser -l /etc/cgconfig.conf 2>&1)
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		fail
		[ "$out" ] && echo >&2 "$out"
		exit $RETVAL
	fi

	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/cgconfig
	ok
}

stop() {
	if [ ! -f /var/lock/subsys/cgconfig ]; then
		msg_not_running "cgconfig"
		return
	fi

	msg_stopping "cgconfig"
	cgclear
	RETVAL=$?
	cgclear
	rm -f /var/lock/subsys/cgconfig
	ok
	umount_cgroup
}

condrestart() {
	if [ ! -f /var/lock/subsys/cgconfig ]; then
		msg_not_running "cgconfig"
		RETVAL=$1
		return
	fi

	stop
	start
}

RETVAL=0
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	if [ -f /var/lock/subsys/cgconfig ] ; then
		echo "Running"
		exit 0
	else
		echo "Stopped"
		exit 3
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
	;;
esac

exit $RETVAL
