#! /bin/sh

# The script is designed to be invoked from a "Makefile",
# notice the command "$MAKE $pgm" below.

MAKE="make --no-print-directory"
ECHO_N="-n"
ECHO_C=""
ECHO_T=""
RM="rm"
MV="mv"

MPE_BINDIR=/usr/bin

execbasename=`basename $0`
MPE_OUTFILE="mpe2_$execbasename.txt"
# If MPERUN is set by configure, it should have been doubly quoted.
MPERUN_DEF=
MPERUN_DEF=${MPERUN_DEF:-"$MPE_BINDIR/mpiexec -n 4"}
MPERUN=${MPERUN:-${MPERUN_DEF}}
CLOG2TOSLOG2=${CLOG2TOSLOG2:-"$MPE_BINDIR/clog2TOslog2"}

pgm=$1
message=$2

# Define clog2 and slog2 filenames based on executable prefix filename.
clog2file="`echo $pgm | sed -e 's/\.exe$//g'`.clog2"
slog2file="`echo $pgm | sed -e 's/\.exe$//g'`.slog2"

echo
echo ${ECHO_N} "$message ${ECHO_C}"
$RM -f $pgm
$MAKE $pgm > $MPE_OUTFILE 2>&1
if test -x $pgm ; then
    $RM -f $MPE_OUTFILE
#   remove the possible clog2 files generated by the subsequent mpiexec run.
    $RM -f Unknown.clog2 $clog2file
    $RM -f Unknown.clog2.pnm ${clog2file}.pnm
    echo "$MPERUN $pgm" > $MPE_OUTFILE
    $MPERUN $pgm >> $MPE_OUTFILE 2>&1
    mperun_rc=$?
    if [ $mperun_rc != 0 ] ; then
        echo "${ECHO_T}No."
        echo "    The failed command is :"
        cat $MPE_OUTFILE 
    else
        if [ -f Unknown.clog2 -a ! -f $clog2file ] ; then
            $MV Unknown.clog2 $clog2file
        fi
        if [ -f $clog2file ] ; then
            echo "${ECHO_T}Yes."
            echo ${ECHO_N} "    Convert $clog2file to slog2 file .............. ${ECHO_C}"
            if [ -x $CLOG2TOSLOG2 ] ; then
                $RM -f $MPE_OUTFILE
                echo "$CLOG2TOSLOG2 $clog2file" > $MPE_OUTFILE
                $CLOG2TOSLOG2 $clog2file >> $MPE_OUTFILE 2>&1
                logconv_rc=$?
                if [ $logconv_rc = 0 -a -s $slog2file ] ; then
                    echo "${ECHO_T}Yes."
                else
                    echo "${ECHO_T}No."
                    echo "        `basename $CLOG2TOSLOG2` conversion fails!" 
                    cat $MPE_OUTFILE 
                fi
            else
                echo "${ECHO_T}No."
                echo "        Missing file or unset execution bit in $CLOG2TOSLOG2!" 
            fi
        else
            echo "${ECHO_T}No."
            echo "   $clog2file is not generated."
        fi
    fi
    $RM -f $pgm
else
    echo "${ECHO_T}No."
    echo "    The failed command is :" 
    cat $MPE_OUTFILE 
fi
$RM -f $MPE_OUTFILE
