#!/bin/sh
# Copyright (c) 2015 Oracle and/or its affiliates. All Rights Reserved.
# Copyright (c) International Business Machines  Corp., 2005
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it would be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Mitsuru Chinen <mitch@jp.ibm.com>

TST_TOTAL=2
TCID=if-mtu-change

. if-lib.sh

# The interval of the mtu change [second]
CHANGE_INTERVAL=${CHANGE_INTERVAL:-5}
CHECK_INTERVAL=${CHECK_INTERVAL:-$(($MTU_CHANGE_TIMES / 100))}
# The array of the value which MTU is changed into sequentially
CHANGE_VALUES="784 1142 426 1500 68 1500 68 748 68 1142 1500"
CHANGE6_VALUES="1280 1445 1335 1390 1500 1280 1500 1280 1335 1500"
[ "$TST_IPV6" ] && CHANGE_VALUES=$CHANGE6_VALUES

test_body()
{
	local cmd_type=$1

	case $cmd_type in
	if_cmd) local cmd_name='ifconfig' ;;
	ip_cmd) local cmd_name='ip' ;;
	*) tst_brkm TBROK "Unknown test parameter '$cmd_type'"
	esac

	local iface=$(tst_iface)
	[ "$TST_IPV6" ] && local netmask=64 || local netmask=16

	tst_resm TINFO "'$cmd_name changes MTU $MTU_CHANGE_TIMES times " \
	               "every $CHANGE_INTERVAL seconds"

	tst_restore_ipaddr || \
		tst_resm TBROK "Failed to set default IP addresses"

	make_background_tcp_traffic

	mtu_array_len=$(echo $CHANGE_VALUES | wc -w)
	local cnt=0
	while [ $cnt -lt $MTU_CHANGE_TIMES ]; do
		sleep $CHANGE_INTERVAL
		local nth=$(($cnt % $mtu_array_len))
		field=$(($nth + 1))
		cnt=$(($cnt + 1))
		mtu=$(echo $CHANGE_VALUES | cut -d ' ' -f $field)
		[ $cnt -eq $MTU_CHANGE_TIMES ] && mtu=1500

		tst_resm TINFO "set MTU to $mtu $cnt/$MTU_CHANGE_TIMES"
		case $cmd_type in
		if_cmd) ifconfig $iface mtu $mtu ;;
		ip_cmd) ip link set $iface mtu $mtu ;;
		esac

		if [ $? -ne 0 ]; then
			tst_resm TFAIL "Failed to change the mtu at $cnt time"
			return
		fi

		check_connectivity $cnt || return

		# Check the background TCP traffic
		pgrep -x tcp_fastopen > /dev/null || make_background_tcp_traffic
	done

	tst_resm TINFO "check connectivity through $iface"
	check_icmpv${ipver}_connectivity $iface $(tst_ipaddr rhost)
	if [ $? -ne 0 ]; then
		tst_resm TFAIL "$iface is broken"
		return
	fi

	tst_resm TPASS "Test is finished correctly"
}

setup

tst_check_cmds ifconfig

test_body 'if_cmd'
test_body 'ip_cmd'

tst_exit
