#!/usr/bin/perl

open($file_in, "IpToCountry.csv");
open($file_out, ">geolocation.db");
open($file_loc, ">geolocation.loc");

my @countries = ();
my $country_last = '';
my $ip_first = 0;
my $ip_last = 0;
my $backlog = 0;

LINE: while(<$file_in>) {
	next LINE if /^#/;
	chomp;
	$line = $_;
	@elements = split(',', $line);
	if($country_last eq '') {
		$ip_first = strip2int(@elements[0]);
		$ip_last = strip2int(@elements[1]);
		$country_last = stripquotes(@elements[4]);
	}
	else {
		$ip_check = strip2int(@elements[0]);
		$country = stripquotes(@elements[4]);
		if( ($country eq $country_last) && ($ip_check == $ip_last+1) ) {
			$backlog = 1;
			$ip_last = strip2int(@elements[1]);
		}
		else {
			$backlog = 0;
			print $file_out "$ip_first $ip_last $country_last\n";
			addcountry($country_last);
			$ip_first = $ip_check;
			$ip_last = strip2int(@elements[1]);
			$country_last = $country;
		}
	}
}

if($backlog == 1) {
	print $file_out "$ip_first $ip_last $country_last\n";
	addcountry($country_last);
}

@countries = sort(@countries);
print $file_loc "geoLocalize(country)\n";
print $file_loc "{\n";
print $file_loc "\tif(!isDefined(country)) country = \"UNKNOWN\";\n";
print $file_loc "\n";
print $file_loc "\tswitch(country)\n";
print $file_loc "\t{\n";

foreach $co (@countries) {
	print $file_loc "\t\tcase \"$co\": return(&\"GEOLOCATION_$co\");\n";
}

print $file_loc "\t\tcase \"UNKNOWN\":\n";
print $file_loc "\t\tdefault: return(&\"GEOLOCATION_UNKNOWN\");\n";
print $file_loc "\t}\n";
print $file_loc "}\n";

close $file_in;
close $file_out;
close $file_loc;

sub addcountry
{
	foreach $co (@countries) {
		if($co eq $_[0]) { return 0; }
	}

	push(@countries, $_[0]);
	return 1;
}

sub strip2int
{
	return int(stripquotes($_[0]));
}

sub stripquotes
{
	return substr($_[0], 1, length($_[0])-2);
}

sub ip2long
{
  return unpack('N', pack('C4', split('\.', $_[0])));
}

sub int2quad
{
	return join('.',unpack('C4', pack("N", $_[0])));
}
