#!/bin/bash
# -----------------------------------------------------------------------------
#
# FDPR-Pro accelorator setup script for hybrid application use.
#
# -----------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5724-S84
# (C) Copyright IBM Corp. 2007,2007 All Rights Reserved
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with
# IBM Corp.
#

declare ARGSTRING=$@
declare APPSTRING=$1
shift
declare APP_ARGS=$@
declare APP_NAME=`basename $APPSTRING`
declare APP_PATH=`dirname $APPSTRING`
declare FDPR_WORKING_DIR=$APP_PATH/fdpr_temp
declare FDPR_SPE_DIR=$FDPR_WORKING_DIR/spe_dir

source $HYBRID_PERF_TOOLS_DIR/perfToolAcceleratorSetup

if [ "$SCRIPT_DEBUG" ] ; then
  echo "fdprproa specific setup ... "
  echo 
  echo "ARGSTRING        = $ARGSTRING"
  echo "APPSTRING        = $APPSTRING"
  echo "APP_NAME         = $APP_NAME"
  echo "APP_PATH         = $APP_PATH"
  echo "APP_ARGS         = $APP_ARGS"
  echo "FDPR_WORKING_DIR = $FDPR_WORKING_DIR"
  echo "FDPR_SPE_DIR     = $FDPR_SPE_DIR"
  echo "OPT_OPTIONS     = $OPT_OPTIONS"
  echo 
fi

# ----------------------------------------------------------
# usage: run_test.sh <fdprpro>
# FDPRPRO should be in the command path or else a full path should be provided
function checkStat () { 
   stat=$1 ; shift ; step=$* ; 
   if [ $stat = 0 ] ; then 
       echo $step passed 
   else
       echo $step failed
       exit 1
   fi
}
# ----------------------------------------------------------

fdprpro=`which fdprpro`
if [ ! -x "$fdprpro" ] ; then 
   echo "missing or not executable fdprpro: $fdprpro"
   exit 1 
fi 

# Combined PPE/SPE application test accel_ppu64

if [ "$SCRIPT_DEBUG" ] ; then
  echo ""
  echo "Combined PPE/SPE application test: "
fi

rm -rf $FDPR_WORKING_DIR
mkdir -p $FDPR_SPE_DIR
file_in=$APPSTRING
file_out=$FDPR_WORKING_DIR/$APP_NAME
echo
echo "file to process: " $file_in
echo "output file:     " $file_out
echo

echo "Starting instrumentation ... "
$fdprpro -a  instr -cell -p $file_in -o $file_out.instr >$file_out.instr.log 2>&1
checkStat $? instrumentation
echo "--> Instrumentation step finished!"

echo "Running instrumented application. Generating profile ..."
$file_out.instr $APP_ARGS > $file_out.instr.out 2>&1 
checkStat $? profiling
echo "--> Profiling complete!"

echo "Optimizing executable ..."
$fdprpro -a opt -cell $OPT_OPTIONS -p $file_in -f $file_out.nprof \
         -o $file_in.opt >$file_in.opt.log 2>&1
checkStat $? optimization
echo "--> Optimization complete!"$

# ./$file_out.fdpr -i 3 -m 128 -s 5 -v -H > $file_out.fdpr.out 2>&
# checkStat $? optimized run

echo "Cleaning up temporary files ..."
rm -rf $FDPR_WORKING_DIR
echo "--> Cleanup complete!"

exit 
