#!/bin/sh

# TURBO_KEEPUP v3.2
# (re)connection script for Belgacom Turboline ADSL
# Author Frederik Questier http://vub.vub.ac.be/~fquestie
# Thanks to Alain.Nissen@ulg.ac.be, the author of turbo_telnet
# Thanks to David Noble, the author of telnet.pl and sock.pl
# No Thanks to Turboline for the many disconnections.

# CHANGE next 2 lines or those hosts will die if this script becomes popular!
pinghost1="195.238.2.51"   # Nearby host with high uptime e.g. ftp.skynet.be
pinghost2="194.7.3.50"     # Nearby host with high uptime e.g. ftp.uunet.be
ISP_IPnr="212.100"         # The IP_nr we expect for our host
INTERFACE="eth0"           # The interface connected to the ADSL modem
DHCP="/sbin/pump"          # Redhat 6.x dhcp client
#DHCP="/sbin/dhcpcd"       # Redhat 5.x dhcp client
LOGFILE="/usr/local/turboline/connection.log"
turbopath="/usr/local/turboline"             # The path of these scripts
UPDATE_DNS="/usr/local/turboline/update_dns" # Dynamic DNS script (optional)

function TELNET_WWW_DNS ()
{
$turbopath/turbo_telnet
message=`$turbopath/turbo_www`
echo $(date '+%a %d/%m/%y %T') "DANA:" $message>>$LOGFILE
nice -10 $UPDATE_DNS &
}

function TEST_CONNECTION ()
{
# ping pinghost1
if [ -z "`/bin/ping -c4 $pinghost1|grep ms`" ]
then
  # ping pinghost2
  if [ -z "`/bin/ping -c4 $pinghost2|grep ms`" ]
  then
    echo $(date '+%a %d/%m/%y %T') "No connection to both testsites">>$LOGFILE
    sleeptime=60   # Don't wait too long for next test 
    return 0 
  else
    sleeptime=600  # Ok, we can wait a bit longer for next test
    return 1
  fi
else
  sleeptime=600    # Ok, we can wait a bit longer for next test
  return 1
fi
}

TEST_IPNR ()
{
# check if we still got IPnr of our provider, and not a Turboline one
if [ -z "`/sbin/ifconfig|grep $ISP_IPnr`" ]
then
   echo $(date '+%a %d/%m/%y %T') "Lost provider IPnr">>$LOGFILE
fi
}
             
# Launch connection
TELNET_WWW_DNS
               
sleep 20

# Check and keep up connection
while true
do
  # check if we still got connection
  if TEST_CONNECTION # fails... 
    then
    TELNET_WWW_DNS
    if TEST_CONNECTION # still fails
    then
	TEST_IPNR # Just wanna log it. So, you could remove this line.       
        # Probably DANA said: Release Ipnr...
        killall -9 turbo_telnet
        $DHCP -k
        $DHCP -i $INTERFACE
        if TEST_CONNECTION # still fails
        then
           /etc/rc.d/rc2.d/S10network restart
           $DHCP -k
           $DHCP -i $INTERFACE
           TELNET_WWW_DNS
           # /etc/rc.d/rc.firewall &   # IP Masquerading and stuff (optional)
           sleeptime=10  # Test immediately again, cause this is bad!
        fi
    fi
  fi
  sleep $sleeptime
done
