#!/bin/sh
# oprofdata-collect2.sh
# runs a series of tests reading what to measure on each run from $1
# $1 name of file holding list of experiments, each line an experiment
# $2 name of file listing session names and experiments
# rest of line is what to run

PREFIX="data"

sudo opcontrol --deinit

set -e
set -x

if [ $# -lt 3 ]; then
    echo "Usage: oprofdata-collect2.sh expfile result file  script_to_run ..."
    exit 1
fi

#which file to read in test setup
EXPERIMENTS_FILE=$1
if [ ! -r $EXPERIMENTS_FILE]; then
    echo "Experiment file " $EXPERIMENTS_FILE " unreadable."
    exit 1
fi

#which file to store the information on which sessions map to sample runs
RESULTS_FILE=$2
echo "Run started" `date` > $RESULTS_FILE

# get the stuff to run
shift 2
INNER=$@

for x in $(seq $(grep -c $ $EXPERIMENTS_FILE))
do
  x=$(($x))
  echo $x
  EVENTS=`sed  -n ${x}p $EXPERIMENTS_FILE`
  echo $EVENTS
  #print out name of run and events being monitored
  echo "$x monitoring $EVENTS"
  sudo opcontrol --setup \
      --vmlinux=/boot/vmlinux-$(uname -r) --separate=library \
      --buffer-size=1000000 \
      $EVENTS
  echo "Starting" `date` >> $RESULTS_FILE
  echo "$EVENTS" >> $RESULTS_FILE
  sudo opcontrol --start
  $INNER
  echo "Finished" `date` >> $RESULTS_FILE
  sudo opcontrol --dump
  sudo opcontrol --shutdown
  #generate a unique name for the file
  SERIAL=`mcookie`
  DATA=$PREFIX.${SERIAL:10:5}
  sudo opcontrol --save=$DATA
  echo "Data saved as $DATA" >> $RESULTS_FILE
done

sudo opcontrol --deinit
