#! /usr/bin/perl
#
$ENV{PATH}="/bin:/usr/bin:/usr/ucb";
$ENV{LD_LIBRARY_PATH}="";
$ENV{LD_PRELOAD}="";


$|=1;

print "Content-type: text/plain\n\n";

if ( $ENV{QUERY_STRING} =~ /^IP=/ ) {
  ($ip=$ENV{QUERY_STRING})=~s/IP=//;
} else {
  $ip="0.0.0.0";
}

$src=$ENV{REMOTE_ADDR};
$ip=~/192.168./ or die "Will not do arbitrary address $ip\n";
( $src ne $ip ) and die "Not authenticated for $ip\n";

$ip=~/(\d+).(\d+).(\d+).(\d+)/;
$key=uc(sprintf "%02x%02x%02x%02x",$1,$2,$3,$4);

print "Resetting installflag on server $ip\n";
print  "  PXELinux host IP hex: $key\n";
printf "  Decimal IP address  : %d.%d.%d.%d\n",$1,$2,$3,$4;

# this was old-style remove-the-pxe-templlate that did not work
#unlink "/tftpboot/pxelinux.cfg/$key" or warn "  Cannot unlink $key: $!\n";

unlink "/etc/dhcpd.conf.bak";
unlink "/etc/dhcpd.conf.new";
link "/etc/dhcpd.conf","/etc/dhcpd.conf.bak" and do {
  $change=0;
  print "  Updating dhcpd.conf file\n";
  open CF,"/etc/dhcpd.conf.bak" or die "Cannot open dhcpd.conf: $!\n";
  open NCF,">/etc/dhcpd.conf.new" or die "Cannot open new dhcpd.conf: $!\n";
  while (<CF>) {
    chomp($_);
    if ( /filename.*#hostip $key/ ) {
      if ( /^#/ ) { print NCF "$_\n"; }
      else { print NCF "#$_\n"; $change++; }
    } else {
      print NCF "$_\n";
    }
  };
  close NCF;
  close CF;
  -s "/etc/dhcpd.conf.new" and do {
    unlink "/etc/dhcpd.conf" and
    link "/etc/dhcpd.conf.new","/etc/dhcpd.conf" and
    unlink "/etc/dhcpd.conf.new";
    $change and ( system("/etc/rc.d/init.d/dhcpd restart") and warn "Cannot restart dhcpd" );
  };

};
