#!/bin/bash

function usage ()
{

    echo "Usage: qprof [OPTION]"
    echo "Arguments are"
    echo -e " -r\t\t\t Use real-time for profiling"
    echo -e " -v\t\t\t Use virtual (user mode) time for profiling"
    echo -e " -i time\t\t Microseconds or events between profiling ticks. \n\t\t\t Default 10,000 usecs or 10,000 events."
    echo -e " -b size\t\t Size of PC sample buffer entries.  Default 400K."
    echo -e " -g gran\t\t Granularity; set to \"instruction\", \"line\" or \"function\""
    echo -e " -a path\t\t Path of addr2line command.  Default /usr/bin/addr2line."
    echo -e " -w col\t\t\t Number of columns in output"
    echo -e " -c color\t\t \"red\" \"blue\" \"green\" or an ECMA color."
    echo -e " -e hwevnt\t\t Hardware event timer (see docs)"
    echo -e " -o file\t\t Output file if not stderr"
    echo -e " -s\t\t\t Include PC values on call stack"
    echo -e " -q dir\t\t\t Directory for q-tools compatible profile information"
}

while getopts "rvi:b:g:a:w:c:e:o:sqh" Option
do
  case $Option in
      h) usage ; exit 0 ;;
      r) export QPROF_REAL=1 ;;
      v) export QPROF_VIRTUAL=1 ;;
      i) export QPROF_INTERVAL=${OPTARG} ;;
      b) export QPROF_BUFFER_SIZE= ${OPTARG} ;;
      g) 
	  case ${OPTARG} in
	      function|line|instruction) export QPROF_GRANULARITY=${OPTARG};;
	      *) 
		  echo "-g must be one of function, line or instruction"
		  exit 1
		  ;;
	  esac ;;
      a) export QPROF_ADDR2LINE=${OPTARG} ;;
      c) export QPROF_COLOR=${OPTARG} ;;
      w) export QPROF_NCOLS=${OPTARG} ;;
      e) export QPROF_HW_EVENT=${OPTARG} ;;
      o) export QPROF_FILE=${OPTARG} ;;
      s) export QPROF_STACK=1 ;;
      q) export QDIR= ${OPTARG} ;;
      *) echo "Invalid option."
	 exit 1;;
  esac
done

#shift so that $1 (and consequently $@) is in the right position
shift $(($OPTIND - 1))

#choosing the version is irrelevant for anything but ia64
if [ -n "$QPROF_ASSUME_KERNEL" ] ; then
    KVER=$QPROF_ASSUME_KERNEL
else
    KVER=`uname -r`
fi

case $KVER in
    2.0.*|2.2.*|2.4.*)
	LIB=libqprof_libpfm2.so
	;;
    2.5.*|2.6.*|2.7.*)
	LIB=libqprof_libpfm3.so
	;;
    *)
	echo "Sorry, your kernel version seems unsupported, please file a bug!"
	exit 1
	;;
esac

# Since this is run as a script, we won't endanger
# the prior setting of LD_PRELOAD, but there may have
# been something useful already set.
LD_PRELOAD=/usr/lib/$LIB:$LD_PRELOAD
export LD_PRELOAD

exec "$@"

