#!/bin/sh
#set -o verbose

function help()
{
cat << EOF
iftero - ifup interface if needed
iftero [--help] [--daemon] [-h] 

Copyright 2004-05-15 Tero.Karvinen <atta> iki.fi
GNU General Public License (version 2 or later)
http://www.iki.fi/karvinen

Iftero determines if network is working. If network is ok, 
iftero does nothing. If network is not working, iftero uses
ifup to restart networking. 

Iftero is especially usefull with networks using dynamic 
DHCP ip-addresses. Without iftero, network does not start working
automatically if network cable is reconnected after it has been
disconnected for a while. Unlike systems that just watch for link 
(network cable) being up, iftero renews ip lease also after 
DHCP server comes up again after being down.

Currently network is considered to be up if primary nameserver
responds to a query. Interface defaults to eth0.

Future versions may explain problems causing network outage
and use more elaborate techniques to determine if net is working. 
EOF
}

function daemon() # run iftero in continously as a daemon or in cron
{
	echo $0;
	#echo "BUG: Overwrites user crontab, if one exists."
	CT=$HOME/.ifterocron
	echo "Adding $0 to crontab to be run every minute..."
	echo "# Run iftero every minute - see: man 5 crontab">$CT
	echo "#M H d m w	Command. Minute Hour day month weekday. ">>$CT
	echo " * * * * *	$0 >/dev/null">>$CT
	crontab $CT
	crontab -l
}

function ifupifneeded() # ifup network if it is not working
{
	IFACE=eth0
	DNS1=`gawk '/nameserver /{print $2}' /etc/resolv.conf|head -1`
	IFUP=/sbin/ifup

	host www.google.com $DNS1|grep "timed out" \
		&& $IFUP $IFACE
}

case "$1" in 
	"") ifupifneeded;;
	"--daemon") daemon;;
	"--help") help;;
	"-h") help;;
#	*) help;;
esac

