#!/bin/sh

# Simple shell script to check whether main link has come back &
# rebuild routing respectively.
# Licence is current GNU GPL.
#(c) Light Olli <olli@digger.org.ru>

# timeout between ping's.
pingtimeout=1

# our main default gateway
gw=212.38.105.1

#### output modifiers.
# enable/disable debugging.
debug=0
# whether we wanna see output from ping & other utils.
silence=0

# null device
null=/dev/null

# paths to utils.
ping=/bin/ping

# done (some 2do are still awaiting their time though)
function check_main_gateway ()
{
 local funcdebug ; funcdebug=1; summ=0; local isup; isup=0; local currmaingw;
 currmaingw=0;
    if [ "$silence" = "1" ]; then
	ping -i $pingtimeout -c 1 -I 212.38.105.2 $gw 1>$null 2>$null 3>$null;
        result=$?;
	[ "$funcdebug" = "1" ] && echo "\$result=$result";
     else
	$ping -i $pingtimeout -c 1  -I 212.38.105.2 $gw;
        result=$?;
	[ "$funcdebug" = "1" ] && echo "\$result=$result";
    fi # [ "$silence" = "1" ]
    if [ "$result" = "1" ]; then 
       isup=0; # not up
       [ "$funcdebug" = "1" ] && echo "\$isup=$isup";
     else
       isup=1; # up
       [ "$funcdebug" = "1" ] && echo "\$isup=$isup";
    fi
    currmaingw=`route -n | grep ^0.0.0.0| grep "UG    0"| awk '{print $2}'`
    [ "$funcdebug" = "1" ] && echo "\$currmaingw=$currmaingw"
    [ "$funcdebug" = "1" ] && echo "\$gw=$gw"
    if [ "$currmaingw" = "$gw" ]; then
        [ "$funcdebug" = "1" ] && echo "Current gw is the same as main one.";
	[ "$funcdebug" = "1" ] && echo "No actions done - all is OK.";
	return 0;
    fi

    if [ "$isup" = "1" ]; then
		echo -e \
    "\nLink on prefferred line has returned. Restoring default parameters..\n";
		change_to_main_link;
		else
			[ "$funcdebug" = "1" ] && echo \
		"Currently main link is still down. No actions done - waiting.";
    fi
}


# Just changes routing to preferred chennel.
function change_to_main_link()
{
 cp	/etc/sysconfig/network.def_gw=212.38.105.1		\
	/etc/sysconfig/network
  cp	/etc/sysconfig/static-routes.primary=212.38.105.1	\
	/etc/sysconfig/static-routes
  /etc/rc.d/init.d/network restart
  route add default gw 195.209.37.25 metric 1
  /etc/rc.d/init.d/firewall+nat.pl start
}

############ programm work start.
check_main_gateway; 
