#!/bin/bash
# StarPU --- Runtime system for heterogeneous multicore architectures.
#
# Copyright (C) 2014-2021  Université de Bordeaux, CNRS (LaBRI UMR 5800), Inria
# Copyright (C) 2014       Université Joseph Fourier
#
# StarPU is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.
#
# StarPU 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 Lesser General Public License in COPYING.LGPL for more details.
#
# Script for giving statistical analysis of the paje trace

set -e # fail fast

# File names
SOURCE_DIR=$(dirname $0)

outputfile="summary.html"
analysis_script="$SOURCE_DIR/starpu_paje_summary.Rmd"
analysis_input=""

# Command line arguments
inputfiles=""

help_script()
{
cat << EOF
Give statistical analysis of the paje trace

Options:
   -h      Show this message

Examples:
$0 example.native.trace
$0 example.native.trace example.simgrid.trace

Report bugs to <starpu-devel@inria.fr>
EOF
}

if [ "$1" = "--version" ] ; then
    echo "$PROGNAME (StarPU) 1.4.1"
    exit 0
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "" ] ; then
    help_script
    exit 0
fi

while getopts "h" opt; do
  case $opt in
    \?)
      echo "Invalid option: -$OPTARG"
      help_script
      exit 3
      ;;
  esac
done

# Reading files that need to be analyzed
shift $((OPTIND - 1))
inputfiles=$@
# Error if there is no input files specified
if [[ $# < 1 ]]; then
    echo "Error!"
    help_script
    exit 2
fi

#####################################
# Transforming input files into .csv
for file in $inputfiles; do
    if [ ! -s $file ]
	then
	echo "Error: file $file does not exist!"
	exit 5
    fi
    dir=$(dirname $file)
    # Sorting traces
    grep -e '^\(\(%\)\|\(\(0\|1\|2\|3\|4\|5\|6\|7\|9\)\>\)\)' $file > $dir/start.trace
    grep -e '^\(\(%\)\|\(\(0\|1\|2\|3\|4\|5\|6\|7\|9\|18\|19\)\>\)\)' -v  $file > $dir/end.trace
    sort -s -V --key=2,2 $dir/end.trace > $dir/endSorted.trace
    cat $dir/start.trace $dir/endSorted.trace > $dir/outputSorted.trace

    # Transferring to .csv
    pj_dump -n $dir/outputSorted.trace > $file.csv
    perl -i -ne 'print if /^State/' $file.csv

    # Cleanup: delete temporary files
    rm -f $dir/outputSorted.trace
    rm -f $dir/start.trace
    rm -f $dir/end.trace
    rm -f $dir/endSorted.trace
done

analysis_input=`echo \"$inputfiles".csv\"" | sed 's/  */.csv", "/g'`

#####################################
# Running analysis file to get actual results
Rscript -e "library(knitr); input_traces = c($analysis_input) ; outputhtml='$outputfile';\
            outputRmd = gsub('.html\$','.Rmd',outputhtml);\
            knit('$analysis_script',output=outputRmd); knitr::knit2html(outputRmd)"

