#!/bin/bash

TOP_DIR=`pwd`

# The first argument is the build plan name which contains
# plan/branch information. We are only interested in the
# last part of this name which is the test name.
TEST=`echo $1 | sed -r 's/.*Build and Test - ([0-9\.]+ - ){0,1}//' | awk '{ print $1; }'`
shift

cd test/core/$TEST

echo "TEST is $TEST"
pwd

# the run-bamboo-test of the performance tests already 
# redirect output to plan.out. no double teeing
PLANFILE=plan.out

#Launch the test
./run-bamboo-test "$@" 

STATUS=$?

#Get RUNDIR from the planning output
RUN_DIR=`grep pegasus-remove $PLANFILE | awk '{print $5}'`
if [ "x$RUN_DIR" = "x" ]; then
    
    # if the workflow was planned with out --submit, it only has a pegasus-run line
    RUN_DIR=`grep pegasus-run $PLANFILE | awk '{print $2}'`

    if [ "x$RUN_DIR" = "x" ]; then
        echo "Unable to determine the RUN_DIR from the planner output - did the planner fail?" 1>&2
        exit 1
    fi
fi

echo "RUNDIR is $RUN_DIR"

# Change in to the rundir
cd $RUN_DIR

SCRIPT_MODE=`grep script braindump.txt`
if [ "x$SCRIPT_MODE" = "x" ]; then
    # check for metrics file consistency with submit files
    # only check for non shell code generator cases
    METRICS_FILE=`ls *metrics 2>/dev/null|  grep -v dag`
    METRICS_TOTAL_JOBS=`grep total_jobs $METRICS_FILE | sed -E "s/.*\"total_jobs\": //"`
    NUM_SUBMIT_FILES=`ls *sub 2>/dev/null| grep -v condor.sub | wc -l | sed -E "s/\s//"`

    if [ $METRICS_TOTAL_JOBS -ne $NUM_SUBMIT_FILES ]; then
	echo "Test failed, the number of submit files $NUM_SUBMIT_FILES does not match total_jobs value $METRICS_TOTAL_JOBS in metrics file $METRICS_FILE"
	STATUS=$(($STATUS + 1))
    fi
fi

if [ $STATUS != 0 ]; then
   echo "Test failed!"
   exit $STATUS
fi

exit
