#!/bin/sh
#
# mount cgroup filesystems per subsystem
#

start() {

    # If /sys/fs/cgroup is mounted, don't mount again
    if [ -n "`grep /sys/fs/cgroup /proc/mounts`" ]; then
        exit 0
    fi

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

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

    # get list of cgroup controllers
    for c in `tail -n +2 /proc/cgroups | awk '{ print $1 }'`; do
        mkdir /sys/fs/cgroup/$c
        mount -t cgroup -o $c cgroup /sys/fs/cgroup/$c
    done

}

stop() {

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

    # Don't try to get too smart, just optimistically try to umount all
    # that we think we mounted
    cd /sys/fs/cgroup
    for d in `tail -n +2 /proc/cgroups | awk '{ print $1 }'`; do
        umount $d || true
    done

    cd ..
    umount /sys/fs/cgroup || true

}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    stop
    start
    ;;
*)
    echo $"Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

exit 0

