#!/bin/bash
# This is the script to start and stop collection of scheduler statistics
#
# reqparam value start|stop|report|postprocess|install Which action you'd like to perform
# reqparam value Collection interval for scheduler statistics
# optparam value Suffix - an optional string to append to the name of the log file 
#

. /etc/autobench.conf || . functions

if [ $# -lt 1 ]; then
  echo "You must specify start, stop, report, postprocess, or install"
  exit 1
fi

CMD="`echo $1 | tr -t A-Z a-z`"

if [ "$CMD" = "start" -a $# -lt 2 ]; then
  echo "You must specify the collection interval for scheduler statistics"
  exit 1
fi

case $CMD in
  install)
    # Install the schedstat helper script if it isn't already...
    getcommand schedstathelper
    ;;

  start)
    # Install the schedstat helper script if it isn't already...
    getcommand schedstathelper

    if [ -n "$3" ]; then
      SUFFIX=".$3"
    fi
    if [ -e /proc/schedstat ]; then
      schedstathelper $2 $SUFFIX &
      echo $! > $TMPDIR/schedstat.pid
    fi
    ;;

  print-start)
    echo 'if [ -e /proc/schedstat ]; then'
    echo '  schedstathelper '$2' $SUFFIX &'
    echo '  echo $! > $TMPDIR/schedstat.pid'
    echo 'fi'
    ;;

  stop)
    if [ -e $TMPDIR/schedstat.pid ]; then
      PID=`cat $TMPDIR/schedstat.pid`
      ps p $PID | grep -q schedstathelper
      if [ $? = 0 ]; then
        kill $PID
      else
        killall schedstathelper 2> /dev/null
      fi
    else
      killall schedstathelper 2> /dev/null
    fi
    ;;

  print-stop)
    echo 'if [ -e $TMPDIR/schedstat.pid ]; then'
    echo '  PID=`cat $TMPDIR/schedstat.pid`'
    echo '  ps p $PID | grep -q schedstathelper'
    echo '  if [ $? = 0 ]; then'
    echo '    kill $PID'
    echo '  else'
    echo '    killall schedstathelper 2> /dev/null'
    echo '  fi'
    echo 'else'
    echo '  killall schedstathelper 2> /dev/null'
    echo 'fi'
    ;;

  report)
    rm $TMPDIR/schedstat.pid > /dev/null 2> /dev/null
    ;;

  postprocess)
    ;;

  *)
    echo "The first argument must be start, stop, report, postprocess, or install"
    ;;
esac
