#! /usr/bin/env mpibash

#####################################
# Invoke all MPI-Bash functions     #
# By Scott Pakin <pakin@lanl.gov>   #
#####################################

# Announce the next test to be performed.
function announce_test () {
    if [ $rank -eq 0 ] ; then
	sleep 1    # Give stdout a chance to drain.
	echo ""
	echo "$@"
    fi
    mpi_barrier
}

# Initialization
enable -f mpibash.so mpi_init
mpi_init
mpi_comm_rank rank
mpi_comm_size nranks
announce_test "Testing mpi_comm_size, mpi_comm_rank, and mpi_barrier:"
echo "    Rank $rank says hello to its $((nranks - 1)) buddies."
if [ $nranks -eq 1 ] ; then
    echo "There's not much to do with only one rank.  Please re-run with more."
    mpi_finalize
    exit 0
fi
rank1=$((rank + 1))

# Send and receive
announce_test "Testing mpi_send and mpi_recv:"
if [ $rank -eq 0 ] ; then
    # Rank 0 receives a message from each rank in turn.
    for (( peer=1; peer<$nranks; peer++ )); do
	mpi_recv $peer msg
	echo "    Rank $rank received the message \"$msg\" from rank $peer."
    done
else
    # All other ranks send a message to rank 0.
    mpi_send 0 "Rank $rank rocks!"
fi

# Broadcast
announce_test "Testing mpi_bcast:"
if [ $rank -eq 0 ] ; then
    mpi_bcast "No, rank 0 rocks!" msg
else
    mpi_bcast msg
fi
echo "    Rank $rank received the broadcast \"$msg\" from rank 0."

# Scan
announce_test "Testing mpi_scan:"
mpi_scan $rank1 sum
echo "    The numbers [1, $rank1] (note closed interval) add up to $sum."

# Exclusive scan
announce_test "Testing mpi_exscan:"
mpi_exscan $rank1 sum
echo "    The numbers [1, $rank1) (note half-open interval) add up to $sum."

# All-reduce
announce_test "Testing mpi_allreduce:"
mpi_allreduce $rank1 sum
echo "    All ranks agree that the numbers [1, $nranks] (note closed interval) add up to $sum."

# Finalize
announce_test "Testing mpi_finalize:"
mpi_finalize
echo "    Goodbye from rank $rank."
