-- ToughLog
\set HOSTNAME `echo "'$HOSTNAME'"`
select syslog('I', :HOSTNAME, 'geoip.sql', 'ID',
'$Id$'
);
select syslog('I', :HOSTNAME, 'geoip.sql', 'INSTALL',
'Install table GeoIP and function GeoIPCountryWhois().'
);

drop function g_GeoIPCountry(inet);
drop table    GeoIP;

create table GeoIP(
	GeoIPID	serial NOT NULL primary key,
	StartIP inet,
	EndIP inet,
	StartRange bigint,
	EndRange bigint,
	Country2 varchar(2),
	Country text
);
create unique index GeoIP_GeoIPID_uix on GeoIP(GeoIPID);

comment on table GeoIP is 'Map between GeoIP and GeoIPID.';
comment on column GeoIP.GeoIPID is 'Unique ID for GeoIP.';

comment on column GeoIP.Country2 is 'Country code in two letter uppercase ISO-3166.';

create function g_GeoIPCountry(inet) returns GeoIP.Country2%type as '
declare
	ip	alias for $1;
	country	GeoIP.Country2%type;
begin
	select Country2 into country from GeoIP where (StartIP<=ip) and (EndIP>=ip);
	if not found then
		country := ''--'';
	end if;
	return country;
end;
' language 'PLpgSQL';

comment on function g_GeoIPCountry(inet) is 'Create GeoIPID and get Country2.';

-- Lookup www.arin.net
select g_GeoIPCountry('69.25.34.202');

--EOF
