#!/bin/bash
#
# Copyright (C) 2004, 2005 Mekensleep
#
# Mekensleep
# 24 rue vieille du temple
# 75004 Paris
#       licensing@mekensleep.com
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
#
# Authors:
#  Loic Dachary <loic@gnu.org>
#
# Each user is responsible for maintaining the benchmark conditions by running
# benchmark -r once to create a benchmark.${LOGNAME} file.
#
#
DRY_RUN=/bin/false
NOT_DRY_RUN=/bin/true
declare -i VERBOSE
VERBOSE=0

: ${srcdir:=.}

set -e

function run() {
    #
    # Make sure everything is loaded in memory
    #
    ${DRY} ./osgcal --benchmark ${srcdir}/data/MC/cal3d.xfg ${srcdir}/data/MC/outfit??.xfg > /dev/null 2>&1
    ${DRY} ./osgcal --benchmark ${srcdir}/data/MC/cal3d.xfg ${srcdir}/data/MC/outfit??.xfg
}

function parse() {
    export IFS=:
    set `grep ':osgcal:' | sed -e 's/\.//g'`
    microseconds=$5
    echo $microseconds
}

function usage() {
    echo "$0: [-h] [-n] [-v verbose] [-r]"
}

REFERENCE=${srcdir}/benchmark.${LOGNAME}

while getopts 'hnv:r' o ; do
  case $o in
      h) usage ; exit 0 ;;
      n) DRY_RUN=/bin/true ; DRY=echo ; NOT_DRY_RUN=/bin/false ;;
      v) 
          VERBOSE=$OPTARG
          set -x
          ;;
      r) 
          run | parse > ${REFERENCE}
          exit 0
          ;;
  esac
done

if [ ! -f ${REFERENCE} ] ; then
    echo "Nothing done"
    echo "You should first create a ${REFERENCE} file with $0 -r"
    usage
    exit 0
fi

declare -i time_to_run reference_time_to_run percent

time_to_run=$(run | parse)
reference_time_to_run=$(cat ${REFERENCE})

let 'difference = time_to_run - reference_time_to_run'
let 'percent = (100 * difference) / reference_time_to_run'

if (( percent > 2 )) ; then
    echo "Performance loss ${percent}%"
    exit 1
elif (( percent < -2 )) ; then
    echo "Performance boost ${percent}%"
    exit 0
else
    (( VERBOSE > 0 )) && echo "Performance stable (variation is ${percent}%)"
    exit 0
fi
