#!/bin/bash
# This script tells autobench to use a particular profiler (when a benchmark
# runs the important section).  If no use/disuseprofiler command are issued,
# the default set of profilers (readprofile, schedstat, sar) are used.
#
# reqparam value command - the name of the command to start/stop/install the profiler
# optparam value repeat arguments - any additional arguments to the profiler (not including a logfile suffix)
#

. /etc/autobench.conf || . functions

if [ $# -lt 1 ]; then
  echo "You must specify a command to execute the profiler"
  exit 1
fi

getcommand startprofilers
getcommand stopprofilers
getcommand disuseprofiler
getcommand $1

# Add it to the list of profilers
if [ -e $TMPDIR/profilers ]; then
  cat $TMPDIR/profilers | grep -v $1 > $TMPDIR/profilers.new
  rm $TMPDIR/profilers
  mv $TMPDIR/profilers.new $TMPDIR/profilers
else
  disuseprofiler readcg
  disuseprofiler sar
  disuseprofiler schedstat
  disuseprofiler readprofile
fi

echo "$@" >> $TMPDIR/profilers

# Add it to the start & stop profilers script
cat $AUTODIR/scripts/startprofilers | grep -v "# $1$" > $TMPDIR/startprofilers.new
rm $AUTODIR/scripts/startprofilers
mv $TMPDIR/startprofilers.new $AUTODIR/scripts/startprofilers

#make sure profile is installed
$($1 install)

ADD=`$1 print-start ${@:2}`
echo "$ADD" | sed -e "s/$/ # $1/" >> $AUTODIR/scripts/startprofilers
chmod a+x $AUTODIR/scripts/startprofilers

ADD=`$1 print-stop ${@:2}`
ADD="`echo "$ADD" | sed -e "s/$/ # $1/"`"

cat $AUTODIR/scripts/stopprofilers | grep -B 99999 "^# ADD NEW STOP LINES HERE$"| grep -v "^# ADD NEW STOP LINES HERE$" | grep -v "# $1$" > $TMPDIR/stopprofilers.new

echo "# ADD NEW STOP LINES HERE" >> $TMPDIR/stopprofilers.new
echo "$ADD" >> $TMPDIR/stopprofilers.new

cat $AUTODIR/scripts/stopprofilers | grep -A 99999 "^# ADD NEW STOP LINES HERE$"| grep -v "^# ADD NEW STOP LINES HERE$" | grep -v "# $1$" >> $TMPDIR/stopprofilers.new

rm $AUTODIR/scripts/stopprofilers
mv $TMPDIR/stopprofilers.new $AUTODIR/scripts/stopprofilers
chmod a+x $AUTODIR/scripts/stopprofilers
