#!/usr/bin/env bash

# JUBE Benchmarking Environment
# Copyright (C) 2008-2015
# Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre
# http://www.fz-juelich.de/jsc/jube
#
# 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 3 of the License, or
# 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, see <http://www.gnu.org/licenses/>.

# This script allows automated full benchmark execution
# Options:
#   -r: additional run args
#   -c: additional continue args
#   -a: additional analyse args
#   -s: additional result args
#   -p: progress check interval in seconds (default:30)
#   -o: only show result output
# Usage: jube-autorun [OPTIONS] input_file.xml

OUTPUT_FILE=jube_job_output.txt
ONLY_RESULT_OUTPUT=0
PROGRESS_INTERVAL=30

# Remove existing output file
if [ -f $OUTPUT_FILE ]
then
  rm $OUTPUT_FILE
fi

# Parse optional arguments
while getopts r:c:a:s:p:o opt
do
	case $opt in
        r) RUN_ARG=$OPTARG;;
        c) CONTINUE_ARG=$OPTARG;;
        a) ANALYSE_ARG=$OPTARG;;
        s) RESULT_ARG=$OPTARG;;
        p) PROGRESS_INTERVAL=$OPTARG;;
        o) ONLY_RESULT_OUTPUT=1;;
        ?) exit 1;;
    esac
done
shift $((OPTIND-1))

# check if input file exists
if [ $# -lt 1 ]
then
	echo "$0: ERROR (MISSING ARGUMENT, PLEASE ATTACH BENCHMARK CONFIG FILE)"
	exit 1
fi

# start benchmark execution
if [ $ONLY_RESULT_OUTPUT -eq 1 ]
then
    jube --force run $1 --hide-animation $RUN_ARG 2>&1 >> $OUTPUT_FILE
else
    jube --force run $1 --hide-animation $RUN_ARG 2>&1 | tee -a $OUTPUT_FILE
fi

# extract benchmark dir
BENCHMARK_DIR=`egrep -o 'handle: .+$' jube_job_output.txt | cut -c9-`

# BENCHMARK_DIR must exist
if [ ! -d "$BENCHMARK_DIR" ]
then
    exit 1
fi

# continue benchmark execution
while [ `jube status $BENCHMARK_DIR` = "RUNNING" ]
do
    sleep $PROGRESS_INTERVAL
    if [ $ONLY_RESULT_OUTPUT -eq 1 ]
    then
        jube --force continue $BENCHMARK_DIR --hide-animation $CONTINUE_ARG 2>&1 >> $OUTPUT_FILE
    else
        echo "Update benchmark information (`date`)"
        jube --force continue $BENCHMARK_DIR --hide-animation --id last $CONTINUE_ARG | tee -a $OUTPUT_FILE
    fi
done

# benchmark analyse
if [ $ONLY_RESULT_OUTPUT -eq 1 ]
then
    jube --force analyse $BENCHMARK_DIR --id last $ANALYSE_ARG 2>&1 >> $OUTPUT_FILE
else
    jube --force analyse $BENCHMARK_DIR --id last $ANALYSE_ARG | tee -a $OUTPUT_FILE
fi

# create benchmark result
jube --force result $BENCHMARK_DIR --id last $RESULT_ARG 2>&1 | tee -a $OUTPUT_FILE
