#!/bin/sh

if [ "$1" = "" ]; then
	echo "Usage: $0 {binary} {files to build the binary}"
	echo "For example:"
	echo "$0 net_test net_test.c ../h/net_test.h"
	echo "All the source code to build net_test must be in net_test.c"
	exit 1
fi

for arg in $*
do
    case $arg in 
    -help | -h | --help | --h | --he | --hel)
	echo "Usage: $0 {binary} {files to build the binary}"
	echo "For example:"
	echo "$0 net_test net_test.c ../h/net_test.h"
	echo "All the source code to build net_test must be in net_test.c"
	exit 0
        ;;
     -v | -version | --v | --version)
        $HMPI_HOME/scripts/hmpi_version_info
        exit 0
        ;;
    esac
done

if [ "$#" = "1" ]; then
	echo "Please input the files used to build the binary"
	echo "Usage: $0 {binary} {files to build the binary}"
	echo "For example:"
	echo "$0 net_test net_test.c ../h/net_test.h"
	echo "All the source code to build net_test must be in net_test.c"
	exit 2
fi

echo ""
echo "====== Copying the files to build binary ======"
echo ""

count1=1
for arg in "$@"
do
	if [ "$count1" = "1" ]; then
		count1=`expr $count1+1`
	else
		echo cp $arg $MPCLOAD/
		cp $arg $MPCLOAD/

		if [ $? -gt 0 ]; then
			echo "Could not copy $arg to $MPCLOAD"
			exit 3
		fi
	fi
done

echo ""
echo "======= \$MPCLOAD ======"
echo "======= $MPCLOAD has files ======="
echo ""
find $MPCLOAD  \( -name '*.c' -o -name '*.h' \)

echo ""
echo "========= Broadcasting files =========="
echo ""

count2=1
for arg in "$@"
do
	if [ "$count2" = "1" ]; then
		count2=`expr $count2+1`
	else
		echo mpcbcast `basename $arg`
		mpcbcast `basename $arg`
		if [ $? -gt 0 ]; then
			echo Error while broadcasting the files
			exit 4
		fi
	fi
done

echo ""
echo "====== Loading/compiling the binaries on the machines ======"
echo ""

hmpiload -o $1 $1.c

if [ $? -gt 0 ]; then
	echo Error while loading the files
	exit 6
fi

echo ""
echo "====== Run the binary ======"
echo ""

echo "mpcrun $1"
hmpirun $1

echo ""
echo "====== Listing, displaying the contents ======"
echo "====== of error files if any            ======"
echo ""

find `pwd` -name '*.err' -exec echo {} \;
find `pwd` -name '*.err' -exec cat {} \;

exit 0
