#!/bin/sh

lockfile=/var/lock/subsys/cgconfig

start() {
  if [ -f $lockfile ] ; then
    echo "lock file already exists"
    exit 0
  fi
  if [ ! -f /proc/cgroups ] ; then
    echo "kernel does not provide cgroups"
    exit 0
  fi
  if ! mountpoint -q /sys/fs/cgroup ; then
    mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup
  fi
  if [ ! -s /etc/cgconfig.conf ] ; then
    echo "/etc/cgconfig.conf is not configured"
    exit 6
  fi
  if ! cgconfigparser -l /etc/cgconfig.conf ; then
    echo "Failed to parse /etc/cgconfig.conf"
    exit 1
  fi
  controllers=`lssubsys -a | tr '\n' ',' | sed 's/,$//'`
  defaultcgroup=""
  if [ -f /etc/cgrules.conf ] ; then
    grep -m1 '^\*[[:space:]]\+' /etc/cgrules.conf \
        | read user ctrl defaultcgroup
    if [ "$defaultcgroup" == "*" ] ; then
      echo $'/etc/cgrules.conf incorrect\nOverriding it'
      defaultcgroup=""
    fi
  fi
  [ -z "$defaultcgroup" ] && defaultcgroup=sysdefault/
  cgcreate -f 664 -d 775 -g $controllers:$defaultcgroup 2> /dev/null
  if echo $controllers | grep -q -w "cpuset" ; then
    cpus=`cgget -nv -r cpuset.cpus /`
    cgset -r cpuset.cpus=$cpus $defaultcgroup
    mems=`cgget -nv -r cpuset.mems /`
    cgset -r cpuset.mems=$mems $defaultcgroup
  fi
  cgclassify -g $controllers:$defaultcgroup `ps --no-headers -eL o tid` \
      2> /dev/null
  if ! touch $lockfile ; then
    echo "Failed to touch $lockfile"
    exit 1
  fi
}

stop() {
  cgclear
  [ -f $lockfile ] && rm -f $lockfile
}

case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  start
  ;;
condrestart)
  if [ -f $lockfile ] ; then
    stop
    start
  fi
  ;;
status)
  if [ -f $lockfile ] ; then
    echo "Running"
  else
    echo "Stopped"
    exit 3
  fi
  ;;
*)
  echo $"Usage: $0 {start|stop|restart|condrestart|status}"
  exit 2
  ;;
esac
exit 0
