#! @SHELL@

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

MAKE="@MAKE@"
ECHO_N="@ECHO_N@"
ECHO_C="@ECHO_C@"
ECHO_T="@ECHO_T@"
RM="@RM@"
MV="@MV@"

MPE_BINDIR=@binbuild_dir@

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

pgm=$1
message=$2

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 $pgm.clog2
    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 $pgm.clog2 ] ; then
            $MV Unknown.clog2 $pgm.clog2
        fi
        if [ -f $pgm.clog2 ] ; then
            echo "${ECHO_T}Yes."
            echo ${ECHO_N} "    Convert $pgm.clog2 to slog2 file .............. ${ECHO_C}"
            if [ -x $CLOG2TOSLOG2 ] ; then
                $RM -f $MPE_OUTFILE
                echo "$CLOG2TOSLOG2 $pgm.clog2" > $MPE_OUTFILE
                $CLOG2TOSLOG2 $pgm.clog2 >> $MPE_OUTFILE 2>&1
                logconv_rc=$?
                if [ $logconv_rc = 0 -a -s $pgm.slog2 ] ; 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 "   $pgm.clog2 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
