#!/bin/bash
# This is the script to start and stop the oprofile profiler.
#
# reqparam value start|stop|report|postprocess|install Which action you'd like to perform
# 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 [ $# -eq 2 ]; then
  SUFFIX=".$2"
fi

OPCTL="$AUTODIR/sources/oprofile/opcontrol"
START_FLAGS=""

REPORT_DEST="\$LOGDIR/analysis/oprofile.\$RUN_NUMBER\$SUFFIX"

function install_profile() {
  # Install oprofile if it isn't already...
  if [ ! \( -d $AUTODIR/sources/oprofile -a -x $AUTODIR/sources/oprofile/opcontrol \) ]; then
     $AUTODIR/scripts/profilers/install/oprofile
  fi

  grep -iq autokern /proc/version
  NOTAUTOKERN=$?
  grep -iq oprofilefs /proc/filesystems
  NEEDOPROMOD=$?


  if [ "$NEEDOPROMOD" == "1" ]; then 
               modprobe oprofile; 
  fi ;
  
  if [ "$NOTAUTOKERN" == "1" ] ; then 
      VMLINUX="/boot/vmlinux-$(uname -r)"  
  else
      VMLINUX="/boot/vmlinux-autobench-$(uname -r)"
  fi
  $OPCTL --shutdown ;
  rm -rf /var/lib/oprofile/samples/current ;
  rm -f ~/.oprofile/daemonrc ;
  $OPCTL --vmlinux=$VMLINUX  ;
  $OPCTL --init ;
}

STOP_STR="$OPCTL --dump ; 
          $OPCTL --stop ; " 



case $CMD in
  install)
    install_profile
    ;;
# start/stop aren't actually used in autobench
#  start)
#        do_arch ;
#	echo "START_FLAGS=$START_FLAGS";
#	/bin/bash -c "$START_STR"
#    ;;
  print-start)

	 # hack to make START_FLAGS work
START_STR="$OPCTL --start &&
		$OPCTL --reset ;" 

	echo "START_FLAGS=\"$START_FLAGS\"";
        echo "$START_STR"
    ;;

#  stop)
#	/bin/bash -c "$STOP_STR"
#    ;;

  print-stop)
    echo "$STOP_STR"
    ;;

  report)
    $AUTODIR/sources/oprofile/opreport -l -p /lib/modules/$(uname -r)/kernel > ${LOGDIR}/analysis/oprofile.${RUN_NUMBER}${SUFFIX} 2>&1 ; 
    ;;

  postprocess)
    $OPCTL --shutdown;
    ;;

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