#!/usr/bin/env bash
trap 'killm f' EXIT
#
# Nate Richard
# JPL
# April 1, 2026
#
# This test pertains to issue #265 "Create Bpdriver commandline option for ttl".
# This test confirms that bpdriver can now send bundles with varying ttl values.


function end(){
    echo
    echo "Stopping ION..."
    cd 1.ipn.bp.udp
    timeout 30 ionexit
    echo "bpdriver TTL test completed."
    exit $RETVAL
}

CONFIGFILES=" \
./1.ipn.bp.udp/config.ionrc \
./1.ipn.bp.udp/config.bprc \
./1.ipn.bp.udp/config.ipnrc"

echo "########################################"
echo
pwd | sed "s/\/.*\///" | xargs echo "NAME: "
echo
echo "PURPOSE: Testing the functionality of issue 265.
        Confirms that bpdriver can now send bundles with varying ttl values.
        This test uses bespokebpv7 to receive BP bundles."
echo
echo "CONFIG: 1 node custom:"
echo
for N in $CONFIGFILES
do
    echo "$N:"
    cat $N
    echo "# EOF"
    echo
done
echo "OUTPUT: Terminal messages will relay results."
echo
echo "########################################"

# Find the latest available Python 3 version >= 3.10
PYTHON_CMD="python3"
MAX_MINOR=-1

check_python_version() {
    local py_exec=$1
    if command -v "$py_exec" &> /dev/null; then
        local py_maj=$("$py_exec" -c 'import sys; print(sys.version_info[0])' 2>/dev/null)
        local py_min=$("$py_exec" -c 'import sys; print(sys.version_info[1])' 2>/dev/null)
        if [ "$py_maj" = "3" ] && [ "$py_min" -ge 10 ]; then
            if [ "$py_min" -gt "$MAX_MINOR" ]; then
                MAX_MINOR=$py_min
                PYTHON_CMD="$py_exec"
            fi
        fi
    fi
}

# Check standard $PYTHON_CMD first
check_python_version $PYTHON_CMD

i=20
while [ $i -ge 10 ]; do
    check_python_version "$PYTHON_CMD.$i"
    i=$((i - 1))
done

if [ -z "$PYTHON_CMD" ]; then
    echo "SKIP: Python 3.10 or higher is required but not found."
    exit 2
fi

PYTHON_VERSION="3.$MAX_MINOR"
echo "Using Python $PYTHON_VERSION (via $PYTHON_CMD)"
echo

./cleanup
RETVAL=1

#Start ION
echo "Starting ion node..."
export ION_NODE_LIST_DIR=$PWD
cd 1.ipn.bp.udp
./ionstart > node.stdout
echo

cd ../

# Test 1 --- Default TTL (300sec)
echo "Test 1 --- Check bpdriver default TTL (300 sec)"
python3 runtest.py 300 -p 4556
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    echo "Test 1 SUCCESS"
    echo
else
    echo "Test 1 FAILURE"
    echo
    end
fi

# Test 2 --- Larger TTL (3000sec)
echo "Test 2 --- Try Increasing bpdriver TTL (3000sec)"
python3 runtest.py 3000 -p 4556
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    echo "Test 2 SUCCESS"
    echo
else
    echo "Test 2 FAILURE"
    echo
    end
fi

# Test 3 --- Smaller TTL (30sec)
echo "Test 3 --- Try Decreasing bpdriver TTL (30sec)"
python3 runtest.py 30 -p 4556
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    echo "Test 3 SUCCESS"
    echo
else
    echo "Test 3 FAILURE"
    echo
fi

end
