#!/bin/sh

# Copyright 2013 Israel Martín Escalona <imartin@entel.upc.edu>
# 
# This file is part of Wipos.
# 
# Wipos is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Wipos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Wipos.  If not, see <http://www.gnu.org/licenses/>.


time_command="/usr/bin/time"
time_command_flags="-f%e"
oFile="simulation"
nArgs=0
device="/dev/pos80211_0"

# Reading the parameters
while getopts ":r:n:o:e:d:a:" optname
  do
    case "$optname" in
      "d")
	device=$OPTARG
        echo "Option $optname has value $OPTARG"
        ;;
      "r")
	runs=$OPTARG
	nArgs=$nArgs+1
        echo "Option $optname has value $OPTARG"
        ;;
      "n")
        samples=$OPTARG
        nArgs=$nArgs+1
        echo "Option $optname has value $OPTARG"
        ;;
      "o")
        oFile="$OPTARG"
        echo "Option $optname has value $OPTARG"
        ;;  
      "e")
        eFile="$OPTARG"
        nArgs=$nArgs+1
        echo "Option $optname has value $OPTARG"
        ;;
      "a")
        additionalArgs="$OPTARG"
        nArgs=$nArgs+1
        echo "Option $optname has value $OPTARG"
        ;;  
      "?")
        echo "Unknown option $OPTARG"
        ;;
      ":")
        echo "No argument value for option $OPTARG"
        ;;
      *)
      # Should not occur
        echo "Unknown error while processing options"
        ;;
    esac
  done
  
if (( (nArgs < 3) )); then
    echo "USAGE: $0 -r runs -n samples -e exec [-o output] [-a args]"
    echo "  r: number of runs to simulate"
    echo "  n: number of samples for each run"
    echo "  e: path of the executable to run"
    echo "  d: device to read"
    echo "  o: path of the file to store the time information"
    echo "  a: optional arguments for the executable"
    exit 1
fi

time_command_flags="${time_command_flags} -o ${oFile}_times.times -a"
  
# Running the measurements
for (( i=1; i <= ${runs}; i++ ))
do
    echo -n "Measuring ${i}/${runs}..."
    `${time_command} ${time_command_flags} ${eFile} ${device} ${samples} ${additionalArgs} > ${oFile}-$i.txt` && echo "[OK]"
done
