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

dummy_systemd() {
  mkdir -p /sys/fs/cgroup/systemd
  if ! mountpoint -q /sys/fs/cgroup/systemd ; then
    if ! mount -n -t cgroup -o none,name=systemd systemd /sys/fs/cgroup/systemd ; then
      rmdir /sys/fs/cgroup/systemd
    fi
  fi
}

start() {
  # if cgroupfs is mounted by fstab, don't run
  if grep -v "^#" /etc/fstab | grep -q "cgroup" ; then
    echo "cgroups mounted from fstab, not mounting /sys/fs/cgroup"
    exit 0
  fi
  # kernel provides cgroups?
  [ -f /proc/cgroups ] || exit 0
  if ! mountpoint -q /sys/fs/cgroup ; then
    mount -t tmpfs -o mode=0755 cgroup /sys/fs/cgroup
  fi
  dummy_systemd

  # get list of cgroup controllers
  for c in `tail -n+2 /proc/cgroups | cut -f1` ; do
    mkdir -p /sys/fs/cgroup/$c
    if ! mountpoint -q /sys/fs/cgroup/$c ; then
      if ! mount -n -t cgroup -o $c cgroup /sys/fs/cgroup/$c ; then
        rmdir /sys/fs/cgroup/$c
      fi
    fi
  done
}

stop() {
  # if /sys/fs/cgroup is not mounted, we don't bother
  mountpoint -q /sys/fs/cgroup || exit 0
  # don't try to get too smart, just optimistically try to umount all
  # that we think we mounted
  for c in `tail -n+2 /proc/cgroups | cut -f1` ; do
    mountpoint -q /sys/fs/cgroup/$c && umount /sys/fs/cgroup/$c
    [ -d /sys/fs/cgroup/$c ] && rmdir /sys/fs/cgroup/$c
  done
  umount /sys/fs/cgroup
}

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

exit 0
