#!/usr/bin/perl -w
###########################################################################
#
# A script reloading your Squid server after dynamic DNS IP has changed
# use a cronjob to execute, maybe every five minutes
#
# (c) 2008 CREEQ <creeq@web.de>
# http://f00l.de
# Visit us: #linux-support @ EFNet
#
###########################################################################

# YOUR dyndns name to check for updates
$dyndns = 'fool.homelinux.org';

# the file to save your last IP in
$lastipfile = 'dyndns_squid_reload.ip';

# cmd to restart the squid server
$squidrestart = '/etc/init.d/squid restart';

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

$|=1;

# get LAST IP
print "Last IP was ... ";
$lastip = `cat $lastipfile 2> /dev/null`;				# get last ip from file
chomp($lastip);
if ($lastip) { print "$lastip\n"; } else { print "not set\n"; }

# fetch CURRENT IP
print "Fetching current IP ... ";
$currentip = `host $dyndns`;						# use host cmd
chomp($currentip);
# fixes different host versions problem
if (index($currentip, "\t") != -1) {
  substr($currentip, 0, rindex($currentip, "\t")+1) = '';
} else {
  substr($currentip, 0, rindex($currentip, ' ')+1) = '';
}
print "$currentip\n";

# RESTART SQUID ?
if ($currentip ne $lastip) {
  print "IPs differ --> Restarting Squid\n";
  system($squidrestart);						# restart squid
  system("echo $currentip > $lastipfile");				# write back current ip
} else {
  print "IPs match\n";
}
