#!/bin/bash
# This script starts and stops the profilers as appropriate.  Use the scripts
# useprofiler & disuseprofiler to specify which profilers you would like to use
# (This files modify $TMPDIR/profilers.  If no such commands are issued, the
# default set of profilers is sar, readprofile, and schedstat)
# FIXME -- There should be no default list of profilers -- this is just backward
# compatibility. (when fixed, you need to fix autorun as well)
#
# Call 'doprofilers start [SUFFIX]' just before the important part of the 
# benchmark within in the benchmark script (or cause it to be called with the 
# streamfilter).  Similarly call 'doprofilers stop [SUFFIX]' just after the
# important part of the benchmark.
# 'doprofilers install' will make sure that the profiler is installed.
# 'doprofilers report' will commit the results to permenant storage
# 'doprofilers postprocess' will do any post processing that the profiler needs
# 'doprofilers finish' is a shortcut, it is the same as: 'doprofilers stop 
# ; doprofilers report ; doprofilers postprocess'
#
# reqparam value start|stop|report|postprocess|finish|install Do the action for all the selected profilers
# optparam value Suffix - an optional string to append to the name of the log file for each profiler
#

. /etc/autobench.conf || . functions

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

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

if [ -r $TMPDIR/profilers ]; then
  CUSTOM_PROFILERS=yes
fi

function do_forward() {
  if [ -z "$CUSTOM_PROFILERS" ]; then
    # Default profilers
    $3 schedstat $1 30 $2
    $3 sar $1 5 $2
    $3 readprofile $1 $2
  else

    # Read the set of profilers out of the file
    cat $TMPDIR/profilers | (
      while read WORD1 REST; do
        $3 $WORD1 $1 $REST $2
      done
    )
  fi
}

function do_backward() {
  if [ -z "$CUSTOM_PROFILERS" ]; then
    # Default profilers
    readprofile $1 $2
    sar $1 5 $2
    schedstat $1 30 $2
  else

    # Read the set of profilers out of the file
    tac $TMPDIR/profilers | (
      while read WORD1 REST; do
        $WORD1 $1 $REST $2
      done
    )
  fi
}

getcommand startprofilers 
getcommand stopprofilers 

case $CMD in
  install)
    # This will install the shell script if it isn't already there
    do_forward arg1 arg2 getcommand
    # This will call the install portion of the shell script
    do_forward install $2
    ;;

  start)
    touch $TMPDIR/profilers_running
    do_forward start $2
    ;;

  stop)
    rm $TMPDIR/profilers_running
    do_backward stop $2
    ;;

  report)
    do_backward report $2
    ;;

  postprocess)
    do_backward postprocess $2
    ;;

  finish)
    do_backward stop $2
    do_backward report $2
    do_backward postprocess $2
    ;;

  *)
    echo "You must specify start, stop, report, postprocess, or install"
    ;;

esac
