#!/bin/bash

IDIR=`dirname $0`
source "$IDIR"/cnt_utils.sh

## TOOL / USAGE / OPTION
TOOL=cnt_owcet
VERSION=0.1

HELP="
version: $VERSION
usage:   $TOOL <working dir> <option>
options:
  -noffx   don't USE the ff files (if any)
  -v/-vv     verbose/more verbose
input: a working dir _cnt-FILE-FUNC,
  properly initialized with cnt_init
  possibly completed with cnt_bounds,
  that MUST contain:
  - $(n_elf file)
  - $(n_ref file)
  - (opt) one or more .ffx files
output: files are added to working dir
  - $(n_lp file)
 - owcet.time    elapsed time passed in owcet
requires:
  - owcet.arm
"

function usage {
   echo "$HELP"
}

USE_FFX=true
DO_LP=true
VERBOSE=

OPTS=`getopt -a -o hv --long noffx,vv,help -n '$TOOL' -- "$@"`
checkret "Error: try '$TOOL -h' for usage"

eval set -- "$OPTS"
while true ; do
case "$1" in
	-h|--help) usage ; exit 0;;
	--noffx) USE_FFX=false; shift ;;
   -v)       VERBOSE=-v; shift ;;
   -vv|--vv) VERBOSE=-vv; shift ;;
	--) shift ; break ;;
esac
done

if [ $# != 1 ]; then
	usage ; exit 0
fi


#-------------------------------
# 0 - GET WORKING DIR
#     deduce BASE and FUNC
#     check necessary files ...
#-------------------------------
ODIR=${1%/}
if [ ! -d "$ODIR" ]; then
	error "Error: can't open dir \"$ODIR\""
fi

# split ODIR
BASE=`base_of_workdir "$ODIR"`
FUNC=`func_of_workdir "$ODIR"`


# INIT ALL VARS
init_vars "$BASE"

echo BASE=$BASE
echo FUNC=$FUNC

ELF=ref_"$BASE".elf
checkfile "$ODIR"/"$ELF" "Error: file \"%s\" is missing"

#============================================
# 1 - PREPARE owcet args ...
#============================================

OARGS=""
OWCET=owcet.arm
checkcommand "$OWCET" "Error: command \"%s\" is missing"

# build lp ?
#LP is a shared named (see utils)
OARGS+=" --add-prop otawa::ilp::OUTPUT_PATH=$LP"

# USE EXISTING ffx ?
# ALL FILES WITH THE ffx extension
# are taken onto account 
# FFX="ref_$BASE.fixed.ffx"
FFX_LIST=
if $USE_FFX ; then
	#for x in $ODIR/*.ffx ; do
	for x in `find "$ODIR" -maxdepth 1 -name "*.ffx"`; do 
		ffx=`basename "$x"`	
		echo "-> add \"$ffx\" to flow facts" 
		FFX_LIST+=" -f $ffx"	
	done
	echo "-> will use $FFX_LIST"
	OARGS+=" $FFX_LIST"
fi

#============================================
# 2 - RUN OWCET
#============================================

(cd  "$ODIR"; /usr/bin/time -f %E -o owcet.time "$OWCET" $OARGS "$ELF" "$FUNC")
checkret "Error: \"$OWCET $OARGS $ELF $FUNC\" failed, abort..."

LP_SOLVE=lp_solve_int
checkcommand "$LP_SOLVE" "Error: command \"%s\" is missing"
BASIC_WCET=basic.wcet

#echo "try to call lp_solve on $LP"
if [ -s "$ODIR/$LP" ]; then
#echo "calling lp_solve"
	(cd  "$ODIR"; "$LP_SOLVE" -S1 "$LP" > "$BASIC_WCET"  )	
fi


echo -n "ELAPSED TIME (OWCET): " 
cat $ODIR/owcet.time
