#!/usr/bin/perl -w

# Script to make link to dynamic ipadress
#
# If the local ip number changes, the
# script will upload a link to this new
# ipnumber as a redirecting html-page
# to a specified webserver via ftp.

# You can for example run this as a
# cronjob like this (runs every minute)
# by adding the following line in
# /etc/crontab
#
# * * * * *       root /path/to/this/file

# Programmed by Daniel Bengtsson
# danielbe@ifi.uio.no

########################################
# Variables to be set
########################################

# Your network interface which shows the external ip
# For example eth0 or ppp0
$device = "eth0";

# ifconfig command
@ifconfig=`/sbin/ifconfig $device`;

# File where current ipnumber will be stored
$ipfile = "/storage/ipnr";

# Local path to save redirecting webpage 
$htmlfile = "/storage/index2.html";

# Your ftp-server which will contain the redirect
$ftpserver = "ftp.webservername.no";

# Your username on the ftp-server
$username = "johnny";

# Password to the ftp-server
# As this is written clearly here remember
# to make this file only root-readable
$password = "secret";

# Directory on webserver
$ftpdir = "www";

# Mail adress of admin to redirect page
# Remember that @ is written \@
$adminmail = "beppe\@wolgers.se";

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

foreach $line (@ifconfig) {
    if($line =~ /inet addr:/) {
        $line =~ /inet addr:([0-9\.]*)/ ;
	$nip=$1; 
	last;
    }
}

#Exit if link is down
if(!$nip) { exit; }

open(IPFILE, $ipfile) ||
    die "Sorry, could not open $ipfile\nYou have to create this file manually by for example the touch command.\n";
read(IPFILE,$ip,20);
close(IPFILE);

if($ip eq $nip) { }
else { 
    print "IP changed from $ip to $nip\n"; 
    print "\nYou recieve this mail because you are listed in /etc/crontab. If you want to be removed you must remove your adress from this file or ask the system administrator.\n"; 
    print "\nLink to new address -> http://$nip\n"; 
    if( sendindex() ) { 
	open(IPFILE, ">$ipfile") ||
	    die "Sorry, could not open $ipfile.\n";
	print IPFILE  "$nip" ;
	close(IPFILE);
    }
}

sub sendindex {

    use Time::localtime;

    $mod = ctime();

    open(HTMLFILE, ">$htmlfile") ||
	die "Sorry, could not open $htmlfile.\n";
    
    print HTMLFILE "
<html>
<head>
<title>Home-Link</title>
</head>
<body>
Connecting to Linux\@Home...
<meta http-equiv=\"Refresh\" content=\"2; URL=http://$nip\">
<P>&nbsp;</P>
Redirection error? Try <a href=\"http://$nip\">this link</a> or send a
<a href=\"mailto:$adminmail\">mail</a>.<br>
<P>Page automatically updated $mod</P>
</body>
</html>
";
    
    close(HTMLFILE);

    use Net::FTP;

    $ftp = Net::FTP->new($ftpserver, Debug => 0);
    if (!$ftp) {
	print "Server could not upload new IP to $ftpserver, will try each minute\n";
	return 0;
    }
    else {
	$ftp->login($username,$password);

	$ftp->cwd($ftpdir);
	$ftp->ascii();
	$ftp->put($htmlfile);
	$ftp->quit;
	return 1;
    }

}