#!/bin/sh

lockfile=/var/lock/subsys/cgred
pidfile=/var/run/cgred.pid

start() {
  if [ -f $lockfile ] ; then
    echo "cgred is already running with PID `cat $pidfile`"
    exit 0
  fi
  if [ ! -s /etc/cgrules.conf ] ; then
    echo "not configured"
    exit 6
  fi
  if ! grep -q "^cgroup" /proc/mounts ; then
    echo "Cannot find cgroups, is cgconfig service running?"
    exit 1
  fi
  if [ -f /etc/cgred.conf ] ; then
    . /etc/cgred.conf
    OPTIONS="$NODAEMON $LOG"
    if [ -n "$LOG_FILE" ] ; then
      OPTIONS="$OPTIONS --logfile=$LOG_FILE"
    fi
    if [ -n "$SOCKET_USER" ] ; then
      OPTIONS="$OPTIONS -u $SOCKET_USER"
    fi
    if [ -n "$SOCKET_GROUP" ] ; then
      OPTIONS="$OPTIONS -g $SOCKET_GROUP"
    fi
  else
    OPTIONS=""
  fi
  cgrulesengd $OPTIONS || exit 7
  touch $lockfile || exit 1
  echo `pidof cgrulesengd` > $pidfile
}

stop() {
  [ -f $pidfile ] || exit 0
  kill -TERM `cat $pidfile` || exit 1
  rm -f $lockfile $pidfile
}

case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  start
  ;;
condrestart)
  if [ -f $lockfile ] ; then
    stop
    start
  fi
  ;;
reload)
  if [ ! -f $lockfile ] ; then
    echo "cgred is not running."
    exit 0
  fi
  kill -SIGUSR2 `cat $pidfile` || exit 1
  ;;
status)
  if [ -f $lockfile ] ; then
    echo "Running"
  else
    echo "Stopped"
    exit 3
  fi
  ;;
*)
  echo $"Usage: $0 {start|stop|restart|condrestart|reload|status}"
  exit 2
  ;;
esac
exit 0
