#!/usr/bin/perl

use Data::Dumper;
use Time::Local;

open(LEASES,"</var/state/dhcp/dhcpd.leases") || die "No leases file\n";

$debug = shift || 1;


while($in = <LEASES>) {

	if(($addr) = $in =~ /lease (.*) {/) {
		$lease{$addr} = {};
		$current_lease = $lease{$addr};
		print "New host: $addr\n" if($debug);
	} else {
		if(($key, $data) = $in =~ /^\s+(starts|ends)\s+(.*)$/) {
			print "key: [$key] data: [$data]\n" if ($debug);
			$current_lease->{$key} = $data;
		} elsif(($key, $data) = $in =~ /^\s+(.*)\s+(.+)$/) {
			print "key: [$key] data: [$data]\n" if ($debug);
			$current_lease->{$key} = $data;
		}
		
		if($in =~ /\s*abandoned.*/) {
			$current_lease->{"abandoned"} = 1;
		}
	}
}

# calculate expiration values

foreach $addr (keys %lease) {
	($end_date, $end_time) = $lease{$addr}->{'ends'} =~ /^.*\s+(.*)\s+(.*).*$/;

	($yy, $mm, $dd) = split(/\//, $end_date);
	($hh, $mn, $ss) = split(/:/, $end_time);
	$mm -= 1;

	print "$addr ends date: $end_date time: $end_time yy: $yy mm: $mm dd: $dd hh: $hh mn: $mn ss: $ss\n" if($debug);
	$now = time();
	$end_unix_time = timegm($ss, $mn, $hh, $dd, $mm, $yy);
	
	$exp = $end_unix_time - $now;

	print "exp: $exp end_unix_time: $end_unix_time now: $now\n" if ($debug);

	$expired = -1 * 86400 * 10;
	$really_expired = -1 * 86400 * 100;

	if($exp < $really_expired) {
		$lease{$addr}->{'massively-expired'} = 1;
	} elsif ($exp < $expired) {
		$lease{$addr}->{'expired'} = 1;
	} else {
		$lease{$addr}->{'not_expired'} = 1;
	}
}


$hosts = 0;
$totalhosts = 0;

foreach $addr (keys %lease) {
	$totalhosts++;
	next if ! defined $lease{$addr}->{'client-hostname'};
	next if $lease{$addr}->{'abandoned'};
	next if $lease{$addr}->{'massively-expired'};

	$hosts++;

	($name) = $lease{$addr}->{'client-hostname'} =~ /"(.*)"/;
	print "Name: $name Addr: $addr\n" if($debug);

	# add your code here to actually do something with this script

}
	

print "Hosts not massively expired: $hosts\nTotal hosts: $totalhosts\n" if($debug);

