#!/bin/bash
# This is the script to start and stop the readprofile 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

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

RAW=$LOGDIR/analysis/profile.raw.$RUN_NUMBER$SUFFIX

case $CMD in
  install)
    install_profile
    ;;
  start)
    if grep -iq " profile=2 " /proc/cmdline; then
      install_profile

      $AUTODIR/sources/readprofile/readprofile -r
      #start readprofile
    fi
    ;;
  print-start)
    echo 'if grep -iq " profile=2 " /proc/cmdline; then'
    echo '  $AUTODIR/sources/readprofile/readprofile -r'
    echo 'fi'
    ;;

  stop)
    if grep -iq " profile=2 " /proc/cmdline; then
      #stop readprofile
      cp /proc/profile $RAW
    fi
    ;;

  print-stop)
    echo 'cp /proc/profile $LOGDIR/analysis/profile.raw.$RUN_NUMBER$SUFFIX 2> /dev/null'
    ;;

  report)
    ;;

  postprocess)
    if grep -iq " profile=2 " /proc/cmdline; then
      if find_system_map; then

        if ! [ -e $LOGDIR/analysis/System.map.$RUN_NUMBER ] ; then
		cp "$SYSTEM_MAP" $LOGDIR/analysis/System.map.$RUN_NUMBER
	fi
        $AUTODIR/sources/readprofile/readprofile -n -m "$SYSTEM_MAP" -p $RAW \
		| sort -nr > $LOGDIR/analysis/profile.text.$RUN_NUMBER$SUFFIX
      	gzip $RAW
      else 
      	echo error locating System.map > $LOGDIR/analysis/profile.text.$RUN_NUMBER$SUFFIX
      fi
    fi
    ;;

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