#!/bin/sh /etc/rc.common

START=01

log() {
	echo "swmodd_cgroup: ${*}" >/dev/console
}

cgroup_remounting_required()
{
	if ! mount |grep -q '/sys/fs/cgroup '; then
		return 1;
	fi

	if grep -v '^#' /etc/fstab | grep -q cgroup; then
		log "fstab mounted system, remounting of cgroup not required"
		return 1
	fi

	if [ ! -d /sys/fs/cgroup ] && [ ! -e /proc/cgroups ]; then
		log "cgroup fs not found"
		return 1
	fi

	umount /sys/fs/cgroup
	return 0;
}

mount_cgroup()
{

	if ! cgroup_remounting_required; then
		log "cgroup remounting not required"
		return 1
	fi

	mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup
	cd /sys/fs/cgroup
	for sys in $(awk '!/^#/ { if ($4 == 1) print $1 }' /proc/cgroups); do
		mkdir -p $sys
		if ! mountpoint -q $sys; then
			if ! mount -n -t cgroup -o $sys cgroup $sys; then
				rm -f $sys || true
			fi
		fi
	done

	if [ -e /sys/fs/cgroup/memory/memory.use_hierarchy ]; then
		echo 1 > /sys/fs/cgroup/memory/memory.use_hierarchy
	fi
}

boot()
{
	mount_cgroup
}
