#!/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=1
TCID=if4-addr-change
TST_CLEANUP="tst_restore_ipaddr"

. test_net.sh

# Broadcast address of the tested network
CHECK_INTERVAL=${CHECK_INTERVAL:-$(($NS_TIMES / 100))}
# Maximum host portion of the IPv4 address on the local host
LHOST_IPV4_HOST_MAX="254"

trap "tst_brkm TBROK 'test interrupted'" INT

tst_check_cmds ifconfig

tst_resm TINFO "ifconfig changes IPv4 address $NS_TIMES times"

tst_restore_ipaddr

check_icmpv4_connectivity $(tst_iface) $(tst_ipaddr rhost) || \
	tst_brkm TBROK "Failed to ping to $(tst_ipaddr rhost)"

local cnt=0
num=1
while [ $cnt -lt $NS_TIMES ]; do
	# Define the network portion
	num=$(($num + 1))
	[ $num -gt $LHOST_IPV4_HOST_MAX ] && num=1

	[ $num -eq $RHOST_IPV4_HOST ] && continue

	# Change IPv4 address
	lhost_ipv4addr="${IPV4_NETWORK}.${num}"

	ifconfig $(tst_iface) $lhost_ipv4addr netmask 255.255.255.0 \
		broadcast 255.255.255.255 || \
		tst_brkm TFAIL "Failed to change into ${lhost_ipv4addr}"

	cnt=$(($cnt + 1))

	[ $CHECK_INTERVAL -eq 0 ] && continue
	[ $(($cnt % $CHECK_INTERVAL)) -ne 0 ] && continue

	tst_resm TINFO "ping from $lhost_ipv4addr to $(tst_ipaddr rhost)"
	check_icmpv4_connectivity $(tst_iface) $(tst_ipaddr rhost) || \
		tst_brkm TFAIL "$(tst_iface) link broken after ${cnt} times"
done

tst_resm TINFO "ping from $lhost_ipv4addr to $(tst_ipaddr rhost)"
check_icmpv4_connectivity $(tst_iface) $(tst_ipaddr rhost) || \
	tst_brkm TFAIL "$(tst_iface) is broken"

tst_resm TPASS "Test is finished successfully"

tst_exit
