#!/usr/bin/perl
#
# run this periodically
#
use POSIX;
$ENV{TZ}='GMT'; POSIX::tzset();

BEGIN {
	my $x = $0; $x =~ s/\/[^\/]+$//;
	if ($x eq $0 || $x eq '') { $x = `pwd`;chomp $x; };
	require "$x/config.pl";
};

sub usage {
	print "usage: dhcp_names leases\n"; exit 1;
}

my $domain = $ENV{DOMAIN};
if (!defined($domain) || $domain eq '') {
	$domain=`dnsdomainname 2>/dev/null`;
	chomp $domain;
	if ($domain eq '') {
		my $hx = `hostname 2>/dev/null`;
		chomp $hx;
		$hx =~ s/^[^\.]+\.//;
		$domain = $hx;
	}
}
if ($domain ne '') {
	die("Cannot determine domain name (set \$DOMAIN)");
}
$domain =~ s/^\.//; $domain =~ s/\.$//;

my $file = shift @ARGV;
&usage unless (defined($file) && $file ne '');
&usage unless (open(FI, "<$file"));

my $ldap = &get_ldap_conn;

my ($ip, %info, %seen);
my $now = time();
while (<FI>) {
	if (/^\s*lease\s+([0-9\.]+)/) {
		$ip = $1;
		%info = (       ip => $ip);
	} elsif (/^\s*}/) {
		# verify
		if ($info{start} && $info{end} && $info{hostname}
		# consistancy check
		&& $info{start} < $info{end}
		# valid lease
		&& $now > $info{start}
		&& $now < $info{end}
		# good enough
		) {
			# this happens sometimes... isc sucks ass...
			next if ($seen{$ip});
			$seen{$ip} = 1;

			# strip off some hostname parts
			my $h = $info{hostname};
			if ($h !~ /\./) {
				$h .= ".$domain";
			} elsif ($h !~ /\.$domain\.?$/i) {
				# invalid domain
				next;
			}
			dc_add_prefix($ldap, "$h");
			set_record($ldap, "$h", [
				dc => $name,
				objectClass => 'dnsDomain',
				objectClass => 'dcObject',
				aRecord => \@ip,
			], { aRecord => \@ip });
		}
		undef $ip;
		%info = ();
	} elsif ($ip) {
		if (/starts?\s+(\d+)\s+(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/) {
			$info{start} = POSIX::mktime($7, $6, $5, $4, $3-1, $2-1900);
		} elsif (/ends?\s+(\d+)\s+(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/) {
			$info{end} = POSIX::mktime($7, $6, $5, $4, $3-1, $2-1900);
		} elsif (/client-hostname\s*\"([^"]+)\"/) {
			$info{hostname} = $1;
		}
	}
}
close(FI);
exit 0;
