#! /bin/sh
# SPDX-License-Identifier: BSD-3-Clause

# Minimal mptcpd start/stop test.
#
# Copyright (c) 2018, 2019, 2021, Intel Corporation

# Non-interactive sudo capable if exit code is 0.
echo Running non-interactive sudo check...
sudo -n echo "    succeeded"
sudo_exit_code=$?

# Detect MPTCP "enabled" sysctl variable name and value.
#   upstream:          net.mptcp.enabled
#   multipath-tcp.org: net.mptcp.mptcp_enabled
variable=`sysctl --names --pattern 'mptcp.(|mptcp_)enabled' net.mptcp`
old_value=`sysctl --values $variable`

disable_value=0
enable_value=1

# "Disabled" value is always 0, but the "enabled" value could be 1 or
# 2, depending on the kernel in use.  For example, the
# multipath-tcp.org kernel "enabled" value could be 1 or 2.  Use the
# old "enabled" value in case it is 2 instead of 1.
if [ $old_value -ne 0 ]
then
    enable_value=$old_value
fi

# @todo It would be better to have some sort of indication that
#       mptcpd is fully up and running rather than timeout after a
#       fixed amount of time like this.
command="timeout --preserve-status \
                 --signal=TERM     \
                 --kill-after=5s   \
                 1s ../src/mptcpd --plugin-dir=$TEST_PLUGIN_DIR"

# Exit status/code
status=0

# Only run the individual enabled/disabled MPTCP test cases if the
# "enabled" value can be set non-interactively, i.e. sudo can be
# executed without a password.  This is mostly useful for automated
# builds.
if [ $sudo_exit_code -eq 0 ]
then
    for value in $disable_value $enable_value
    do
	sudo -n sysctl -qw $variable=$value

	$command
	command_exit=$?

	echo -n "TEST CASE: $variable = $value ..."

	if ([ $value -eq $disable_value ] && [ $command_exit -eq 0 ]) \
	   || ([ $value -eq $enable_value ] && [ $command_exit -ne 0 ])
	then
	    echo failed
	    status=1   # failure
	else
	    echo passed
	fi
    done

    # Reset the "enabled" value to its original value.
    sudo -n sysctl -qw $variable=$old_value
else
    # Non-root case.
    echo Running test without root privileges
    $command
fi

exit $status
