#!/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.3

exit 123

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

# where testconnec should display debug messages
LOGGER="#"
if [ $DEBUG == 1 ]; then
	LOGGER="logger"
elif [ $DEBUG == 2 ]; then
	LOGGER="echo"
fi

$LOGGER "====== testconnec : begin ======"

# testconnec already launched => quit
LOCK_FILE=/var/run/LCK.testConnec
if [ -e $LOCK_FILE ]; then
	$LOGGER "testconnec is already launched (it should never happend) => quit"
	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

# quit if the modem is not operationnal
RES="`$EAGLESTAT | grep "$OPER_STR"`"
if [ -z "$RES" ] ; then
	$LOGGER "Le modem ne semble pas tre branch..."
	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
	$LOGGER "Connection seems to be lost, restarting it!"
	fctStopAdsl
	sleep 2
	fctStartAdsl
else
	$LOGGER "Connection is still valid ($CPT)"
fi

$LOGGER "====== testconnec : end ======"

rm -f $LOCK_FILE
