#!/s/std/bin/perl -w

use strict;
use File::Copy;
use CSL::DBs;
use CSL::Pg;
use DBI;

my $dbhp = DBI->connect($CSL::DBs::csdb);
my $hdr = "dhcpd.header";
my $mutable = "dhcpd.safe";
my $filename = "dhcpd.conf";
my $dhcpd_host = "dhcp.cs.wisc.edu";

my $splat = $dbhp->selectall_arrayref("select h.hostname, m.mac_address from splat.hostnames h, splat.mac_addresses m where h.part = m.part and h.interface_number = m.interface_number order by hostname asc");

copy($hdr, $filename) or die($!);


open(my $fh, ">>/u/p/e/petska/splat/$filename") or die("Could not open the specified file: $!");
open(my $mh, $mutable);

my @mutable = <$mh>;
print $fh $_ foreach (@mutable);

close($mh);

foreach (@$splat) {
  my $hostname = $_->[0];
  my $macaddr = $_->[1] || next;

  next if ($macaddr eq '-1' || $macaddr eq '00:00:00:00:00:00');
#  next if $hostname !~ s/\.cs\.wisc\.edu//;
  next if $hostname !~ /^[\w.-]*$/;

  my $frag = <<EOF;
host $hostname {
  hardware ethernet $macaddr;
  fixed-address $hostname;
}
EOF

  print $fh $frag;
}
close($fh);

copy("/u/p/e/petska/splat/dhcpd.conf", "/s/dhcp/conf/dummy.conf");

my $dhcpd_bin = "/var/adm/dhcpd/dhcpd";
my $dhcpd_conf = "/s/dhcp/conf/dummy.conf";

my $cmd = qq{ssh -l root $dhcpd_host <<EOF
$dhcpd_bin -t -cf $dhcpd_conf && echo SUCCESS
EOF};

my $exitcode = system($cmd) / 256;
