#! /usr/bin/perl -w
use strict;

my $date = `date --rfc-2822`;
chomp $date;

my @nets = ();
open NAMES, "switches.txt"
	or die "switches.txt: $!";
while (<NAMES>) {
	chomp;
	/87\.76\.(\d+\.\d+)\s+(\d+)\s+(\S+)/ or next;
	push @nets, {
		net => $1,
		netmask => $2,
		name => $3
	};
}	

print <<"EOF";
# Autogenerated by make-dhcpd.pl at $date. Do not edit manually!

option domain-name "tg07.gathering.org";
option domain-name-servers 87.76.254.2, 87.76.255.2;

# Netboot FTW
next-server 87.76.255.18;
filename "/pxelinux.0";

ddns-update-style interim;
omapi-port 7911;

# dnssec-keygen -a HMAC-MD5 -b 128 -n HOST DHCP_UPDATER
key DHCP_UPDATER {
        algorithm HMAC-MD5.SIG-ALG.REG.INT;
	secret F388UOhaIIKHRH9TDE5PTA==;
}

default-lease-time 14400;
max-lease-time 28800;

# Tele-nett
subnet 87.76.254.0 netmask 255.255.255.0 {
}

# Server-nett
subnet 87.76.255.0 netmask 255.255.255.0 {
}

zone 76.87.in-addr.arpa. {
	primary 127.0.0.1;
	key DHCP_UPDATER;
}

EOF

for my $net (@nets) {
	my $domain = $net->{name};

	my ($netmask, $numpc);
	if ($net->{netmask} == 24) {
		$netmask = "255.255.255.0";
		$numpc = 256;
	} elsif ($net->{netmask} == 25) {
		$netmask = "255.255.255.128";
		$numpc = 128;
	} elsif ($net->{netmask} == 26) {
		$netmask = "255.255.255.192";
		$numpc = 64;
	} else {
		die "Unknown netmask /" . $net->{netmask};
	}

	$net->{net} =~ /(\d+)\.(\d+)/ or die "Unknown net $net";
	my ($majorsubnet,$minorsubnet) = ($1,$2);

	# FIXME: Should use Net::CIDR
	my $gw = "87.76.$majorsubnet." . ($minorsubnet + 1);
	my $rangestart = "87.76.$majorsubnet." . ($minorsubnet + 10);
	my $rangeend = "87.76.$majorsubnet." . ($minorsubnet + $numpc - 2);

	print <<"EOF";
zone $domain.tg07.gathering.org. {
	primary 127.0.0.1;
	key DHCP_UPDATER;
}
subnet 87.76.$net->{net} netmask $netmask {
	authoritative;
	option routers $gw;

	range $rangestart $rangeend;
	option domain-name "$domain.tg07.gathering.org";
	ddns-domainname "$domain.tg07.gathering.org";
	ignore client-updates;
}
EOF
}

