#!/usr/bin/perl -w

# $Id: watchDhcp.pl,v 1.4 2001/04/22 17:43:06 resark Exp resark $

$oldIPFilename = "/root/dhinfo/oldIP";	# dir to store state info
$email = "YOUR EMAIL HERE";		# address to notify changes
$subject = "IP Change";
$link = "rl0";				# name of link to watch
$mac = "fe80::202:2aff:fe";		# MAC of link to watch as displayed
					# by netstat

sub GetIP
{
	my $currentIP;

	open(NETSTAT,"netstat -in|");

	while (<NETSTAT>)  {
		if ((/$link/)&&(!(/$mac/))&&(!(/<Link>/)))  {
			my @data = split;
			if ($data[3] =~ /\d/)  {
				$currentIP = $data[3];
			}
		}
	}

	close(NETSTAT);

	return($currentIP);
}

sub GetOldIP
{
	open(OLDIP,$oldIPFilename);
	my $oldIP = <OLDIP>;
	close(OLDIP);

	return($oldIP);
}

sub MailChanges
{
	$currentIP = shift;

	my $msg = sprintf("IP change for YOUR MACHINE NAME.  New IP is \n\t%s",
		       $currentIP);

	my $command = sprintf("echo \"%s\" | mail -s \"%s\" %s",
		       $msg,$subject,$email);

	system($command);
}

sub WriteNewIP
{
	my $currentIP = shift;

	open(FILE,">" . $oldIPFilename);
	print FILE $currentIP;
	close(FILE);
}

sub RestartIpf
{
	system("/sbin/ipf -Fya -f /etc/ipf.rules -E");
}

sub RestartNat
{
	system("/sbin/ipnat -FC -f /etc/ipnat.rules");
}


################

my $currentIP = GetIP();
my $oldIP = GetOldIP();

if ($currentIP ne $oldIP)  {
	MailChanges($currentIP);
	WriteNewIP($currentIP);
	RestartIpf();
	RestartNat();
}