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

drop function cg_RemoteIPID(RemoteIP.RemoteIP%type);
drop table    RemoteIP;

create table RemoteIP(
	RemoteIPID	serial primary key,
	riCreated	timestamp with time zone DEFAULT now(),
	RemoteIP	inet unique NOT NULL,
	Country2	varchar(2) default NULL, -- REFERENCES GeoIP -- Based on WhoIS lookup, see table::nboc
	RevDNS		text,
	RevDNSTime	timestamp with time zone default(NULL)
);
create unique index RemoteIP_RemoteIPID_uix on RemoteIP(RemoteIPID);
create unique index RemoteIP_RemoteIP_uix on RemoteIP(RemoteIP);

comment on table RemoteIP is 'Map between RemoteIP and RemoteIPID.';
comment on column RemoteIP.RemoteIPID is 'Unique ID for RemoteIP.';
comment on column RemoteIP.RemoteIP is '.';
comment on column RemoteIP.RevDNSTime is 'Date and time when the last DNS lookup was made.';

create function cg_RemoteIPID(RemoteIP.RemoteIP%type) returns RemoteIP.RemoteIPID%type as '
declare
	p_ip	alias for $1;
	v_id	RemoteIP.RemoteIPID%type;
	v_ip	RemoteIP.RemoteIP%type;
begin
	if p_ip is null then
		v_id := NULL;
	else
		select RemoteIPID into v_id from RemoteIP where (RemoteIP = p_ip);
		if not found then
			insert into RemoteIP (RemoteIP, Country2) values(p_ip, g_GeoIPCountry(p_ip));
			select last_value into v_id from RemoteIP_RemoteIPID_seq;
		end if;
	end if;
	return v_id;
end;
' language 'PLpgSQL';

comment on function cg_RemoteIPID(RemoteIP.RemoteIP%type) is 'Create RemoteIPID and get RemoteIP.
SELECT cg_RemoteIPID(''12.34.56.78'')
or
INSERT INTO HttpLog(RemoteIPID) VALUES(cg_RemoteIPID(''12.34.56.78''))';

select cg_RemoteIPID('127.0.0.1');

--EOF
