#!/usr/bin/env bash
trap 'killm f' EXIT
#
# AMS SANA (i.e. node number upgrade) integration test script
# This test uses amsbenchr and amsbenchs over LTP protocol
# AMS Continuum numbers 9999 and 32767 are used
#
# Sky DeBaun
# January 2022
#
# Test boilerplate per Scott Burleigh


# Variables for message count (and size)
COUNT=100
BYTES=1024


stop_and_exit()
{
    if [ "$1" -eq 0 ]; then
        echo -e "\nAMS SANA TEST SUCCESS!!!\n"
    else
        echo -e "\nAMS SANA TEST FAILURE!!!\n"
    fi

    ./shutdown_proc
    exit $1
}

CONFIGFILES=" \
./amroc.ltprc \
./amroc.bprc \
./global.ionrc \
./amroc.ionrc \
./amroc.ionconfig \
./amroc.ionsecrc \
./amroc.ipnrc \
./mib.amsrc
"
echo -e "\n################################################################################"
TEST_NAME=$(pwd | sed "s/\/.*\///")
echo "TEST NAME: $TEST_NAME"

echo -e "PURPOSE: Verify AMS functionality when using large Node numbers\n"
sleep 2

for N in $CONFIGFILES
do
    echo "$N:"
    cat $N
    echo "# EOF"
    echo
done

echo -e  "\n################################################################################"
echo > ion.log
./cleanup
sleep 1

echo "Starting ION..."
export ION_NODE_LIST_DIR=$PWD

# Start ION nodes and verify
./ionstart
sleep 1

# Start message logger
echo -e "\nStarting AMSBENCH Receiver."
amsbenchr > test_output &
sleep 2

# Start message transmitter with variables
echo -e "\nStarting AMSBENCH Transmitter."
echo -e "Sending $COUNT messages (of $BYTES bytes each)"
amsbenchs $COUNT $BYTES > /dev/null &
sleep 2

# Test result variable
RETVAL=0 # Default to success

# Get message count using variables and arithmetic for total bytes
EXPECTED_BYTES=$((COUNT * BYTES))
MSG_PATTERN="Received $COUNT messages, a total of $EXPECTED_BYTES bytes"

echo -e "\nAnalyzing Receiver output:"
sleep 1
RESULT=$(grep "$MSG_PATTERN" test_output | wc -l)
cat test_output


# Shut down and cleanup
echo -e "\nTest transmission(s) complete - please standby for results:\n"

# shutdown ams daemons explicitly (not absolutely necesary)


# Test complete: report test result
echo -e "\n################################################################################"
echo -e "$TEST_NAME test complete:"


if [ "$RESULT" -eq 1 ]
then
    echo -e "$COUNT test messages received ($EXPECTED_BYTES bytes total)."
else
    echo "ERROR: Messages not received."
    # Failure to deliver occurred
    RETVAL=1
fi

stop_and_exit $RETVAL
