#!/bin/sh
##set -x
##set -u
IFCONFIGCMD=/sbin/ifconfig
err=0

#	LINKSYS BEFSR41C-JPV2
#	COREGA  CG-BAR FX2
MYIP0=192.168.1.20
MYIP1=192.168.1.21
SVIP=192.168.1.1
#	BUFFERLOW BBR-4MG
#MYIP=192.168.11.20
#SVIP=192.168.11.1


if [ X$2 != X ];then
	DEBUG=$2
else
	DEBUG=
fi
if [  X$1 = Xeth0 ];then
  MYIP=${MYIP0}
  ethn=$1
elif [  X$1 = Xeth1 ];then
  MYIP=${MYIP1}
  ethn=$1
else
  MYIP=${MYIP1}
  ethn=eth2
fi
#-------
wget_sv()
{
	svpwd='pwd'
	cd /tmp
#	
# BUFFERLOW BBR-4MG
#	/bin/wget http://${SVIP}/ 
#
# LINKSYS BEFSR41C-JPV2
#	/bin/wget --http-user=admin --http-passwd=admin http://${SVIP}/ 
#
# COREGA  CG-BAR FX2
	/bin/wget --http-user=root --http-passwd= http://${SVIP}/ 
	res=$?
	ls -l
	cd ${svpwd}
	return $res
}
#-------
#echo -n "ETHER  ${ethn}             ..."

if ! ${IFCONFIGCMD} ${ethn} > /dev/null 2>&1; then 
	echo "ERROR (no device)"
	err=`expr $err + 1`
else
	if (${IFCONFIGCMD} ${ethn} | grep UP) > /dev/null 2>&1; then
		have_static_address=1
		${IFCONFIGCMD} ${ethn} add ${MYIP}

		arp -d ${SVIP} > /dev/null 2>&1
	else
		have_static_address=0
		${IFCONFIGCMD} ${ethn} ${MYIP}
	fi
	if [ X${DEBUG} = X1 ];then
		echo "have_static_address=${have_static_address}"
		echo "MYIP=${MYIP}"
		echo "ethn=${ethn}"
		route
		arp
	fi

	let pin_stat=1
	let RetryCnt=0
	while [ ${RetryCnt} -lt 10 ] ; do
		RetryCnt=`expr ${RetryCnt} + 1`
		ping -c 2 -w 2 ${SVIP} > /dev/null 2>&1
		pin_stat=$?
		if [ ${pin_stat} -eq 0 ] ; then
			break;
		fi
	done
	if [ X${DEBUG} = X1 ];then
		echo "RetryCnt=${RetryCnt}"
		echo "pin_stat=${pin_stat}"
	fi
	
	if [ $pin_stat -ne 0 ] ; then
		echo "ERROR (ping err)" 
		err=`expr $err + 1`
	else
		ping -c 1 -w 1 ${SVIP} > /dev/null 2>&1
		let get_stat=1
		let RetryCnt=0
		while [ ${RetryCnt} -lt 3 ] ; do
			RetryCnt=`expr ${RetryCnt} + 1`
			wget_sv > /dev/null 2>&1;
			get_stat=$?
			if [ ${get_stat} -eq 0 ] ; then
				break;
			fi
		done
		if [ X${DEBUG} = X1 ];then
			echo "RetryCnt=${RetryCnt}"
			echo "get_stat=${get_stat}"
		fi
		if [ ${get_stat} -ne 0 ] ; then
			echo "ERROR (http get)"
			err=`expr $err + 1`
		fi
	fi
	if [ x$err = x0 ]; then
		echo "OK"
	fi
	if [ X${DEBUG} = X1 ];then
		${IFCONFIGCMD} 
		if [ x$err != x0 ]; then
			exit $err
		fi
	fi
	if [ $have_static_address = 1 ]; then
		${IFCONFIGCMD} ${ethn}:0 down
	else
		${IFCONFIGCMD} ${ethn} down
	fi
	if [ X${DEBUG} != X ];then
		${IFCONFIGCMD} 
		route
		arp
	fi
fi

exit $err


