#! /usr/bin/perl

print "begin;\n";
print "delete from temppoll;\n";
print "delete from placements;\n";
print "delete from dhcp;\n";
print "delete from switches;\n";
print "SELECT pg_catalog.setval('switches_switch_seq', 1, false);\n";
print "SELECT pg_catalog.setval('polls_poll_seq', 1, false);\n";

open PATCHLIST, "patchlist.txt"
	or die "patchlist.txt: $!";

my $i = 1;
while (<PATCHLIST>) {
	chomp;
	my ($name, $distro, $port) = split / /;

	$name =~ /e(\d+)-(\d+)/;
	my ($e, $s) = ($1, $2);

	my $x = int(244 + $e * 9.87);
	my $y;

	$x += 7 if ($e >= 19);
	$x += 14 if ($e >= 35);
	$x += 9 if ($e >= 51);
	$x += 9 if ($e >= 68 && $s < 4);

	my ($c, $d);
	if ($s <= 3) {
		$c = $e;
		$d = ($s - 1) * 64;

		$y = 455 - $s * 48;
	} else {
		$c = $e + 1;
		$d = ($s - 4) * 64;

		$y = 424 - $s * 48 - ($s - 3) * 2;
	}

	my $xx = $x + 12;
	my $yy = $y + (($s > 3) ? 50 : 48);

	my ($ip, $range);
	if ($s == 1) {
		$ip = "87.76." . ($e) . ".2";
		$range = "87.76." . ($e) . ".0";
	} elsif ($s == 2) {
		$ip = "87.76." . ($e) . ".66";
		$range = "87.76." . ($e) . ".64";
	} elsif ($s == 3) {
		$ip = "87.76." . ($e) . ".130";
		$range = "87.76." . ($e) . ".128";
	} elsif ($s == 4) {
		$ip = "87.76." . ($e + 1) . ".2";
		$range = "87.76." . ($e + 1) . ".0";
	} elsif ($s == 5) {
		$ip = "87.76." . ($e + 1) . ".66";
		$range = "87.76." . ($e + 1) . ".64";
	} elsif ($s == 6) {
		$ip = "87.76." . ($e + 1) . ".130";
		$range = "87.76." . ($e + 1) . ".128";
	}

	print "insert into switches (ip, sysname, switchtype) values ('$ip', 'e$e-${s}sw', 'es3024');\n";
	print "insert into placements (switch, placement) values ($i, box '(($x,$y),($xx,$yy))');\n";
	print "insert into dhcp (switch, network) values ($i, '87.76.$c.$d/26');\n";
	$i++;
}

print "end;\n";
