#!/bin/bash
# Name: testConnec
# Goal: use ping to ensure that the connection is valid
# Author: Tux - Thanks to baud123 for ping_w() function.
# Version: 1.9.5
# 

. /etc/eagle-usb/scripts/setvars

for param in $* ; do
	if [ $i -gt 0 ] ; then
			param=${param//--help/-h}
			param=${param//--iplist=/-l}
			param=${param//--debug=/-d}
			PARAMS="$PARAMS $param"
	fi
	let i++
done
evalParams() {
	while getopts "hl:d:" opt; do
		case $opt in
			h  )	echo -e $TESTCONNEC_USAGE_MSG ; exit 0 ;;
			l  )	TESTIP="$OPTARG" ;;
			d  )	DEBUG=$OPTARG ;;
			\? )	echo -e $TESTCONNEC_USAGE_MSG ; exit 1 ;;
		esac
	done
}
DEBUG=0
TESTIP="213.228.0.42 216.239.37.99"
evalParams $PARAMS

echo_log "====== testconnec : begin ======"

# testconnec already launched => quit
LOCK_FILE=/var/run/LCK.testConnec
if [ -e $LOCK_FILE ]; then
	echo_log "testconnec is already launched (it should never happend) => quit" 1
	exit 1
fi

# testconnec is only enabled when "start_on_boot" is enabled too
if [ $START_ON_BOOT == 0 ] ; then
	exit 0
fi

# prevent this script from being launch 2 times simultaneously
touch $LOCK_FILE
chmod a+rw $LOCK_FILE

# modem crashed when booting?
if $EAGLESTAT | grep -q "${BOOTING_STR}" ; then
	sleep 5s
	# still booting after 5s => crashed
	if $EAGLESTAT | grep -q "${BOOTING_STR}" ; then
		echo_log "Modem crashed! rebooting..."
		fctStopAdsl
		$EAGLECTRL -w 1>/dev/null 2>/dev/null
		if [ $? != 0 ] ; then
			exit 1
		fi
	fi
fi

# quit if the modem is not operationnal
RES="`$EAGLESTAT | grep "$OPER_STR"`"
if [ -z "$RES" ] ; then
	echo_log "Modem is not plugged..."
	rm -f $LOCK_FILE
	exit 0
fi

OK="no"

declare -i CPT
CPT=0

for i in $TESTIP; do
	if [ "$OK" = "no" ]; then
		ping_w $i 5
		if [ $? == 0 ]; then
			OK="$i"
		fi
		CPT=$(($CPT+1))
	fi
done

if [ "$OK" = "no" ] ; then
	echo_log "Connection seems to be lost, restarting it!"
	fctStopAdsl
	sleep 2
	fctStartAdsl
else
	echo_log "Connection is still valid ($CPT)"
fi

echo_log "====== testconnec : end ======"

rm -f $LOCK_FILE
