#!/usr/bin/perl -sw

my $mode = 1;
my $line = 1;

printf("BEGIN Work;\n");
printf("DROP INDEX GeoIP_StartIP;\n");
printf("DROP INDEX GeoIP_StartRange;\n");
printf("DROP INDEX GeoIP_EndIP;\n");
printf("DROP INDEX GeoIP_EndRange;\n");
printf("COMMIT Work;\n");

printf("BEGIN Work;\n");
printf("TRUNCATE GeoIP;\n");
if ($mode eq 1) {
	printf("COPY geoip (geoipid, startip, endip, startrange, endrange, country2) FROM stdin;\n");
	printf($line++."\t10.0.0.0\t10.255.255.255\t167772160\t184549375\t_a\n");
	printf($line++."\t172.16.0.0\t172.31.255.255\t2886729728\t2887778303\t_b\n");
	printf($line++."\t192.168.0.0\t192.168.255.255\t3232235520\t3232301055\t_c\n");
}
while (<>) {
	# "2.6.190.56","2.6.190.63","33996344","33996351","GB","United Kingdom"
	if (/^"([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)"/) {
		if ($mode eq 0) {
			printf("INSERT INTO GeoIP(StartIP,EndIP,StartRange,EndRange,Country2)");
			printf(" VALUES('$1', '$2', $3, $4, '$5');\n");
		} else {
			#1       2.6.190.56      2.6.190.63      33996344        33996351        GB
			printf("$line\t$1\t$2\t$3\t$4\t$5\n");
		}
	}
	$line++;
}
if ($mode eq 1) {
	printf("\\.\n");
	printf("ALTER SEQUENCE geoip_geoipid_seq RESTART WITH $line;\n");
}
printf("COMMIT Work;\n");

printf("BEGIN Work;\n");
printf("CREATE INDEX GeoIP_StartIP ON GeoIP(StartIP);\n");
printf("CREATE INDEX GeoIP_StartRange ON GeoIP(StartRange);\n");
printf("CREATE INDEX GeoIP_EndIP ON GeoIP(EndIP);\n");
printf("CREATE INDEX GeoIP_EndRange ON GeoIP(EndRange);\n");
printf("COMMIT Work;\n");
