# Print the country name in /WHOIS replies
# /GEOIP <ip/host> prints the country name for the host/ip
# /SET geoip_dat /full/path/to/GeoIP.dat
#
# http://www.maxmind.com/download/geoip/database/GeoIP.dat.gz

use strict;
use Geo::IP;
use Irssi;
use Socket;

use vars qw($VERSION %IRSSI);
$VERSION = "0.0.3";
%IRSSI = (
    authors         => "Toni Viemerö",
    contact         => "toni.viemero\@iki.fi",
    name            => "geoip",
    description     => "Print the users country name in /WHOIS replies",
    license         => "Public Domain",
    changed         => "Wed Nov 19 14:34:12 EET 2003"
);

sub event_whois {
    my $country = "";
    my $database = Irssi::settings_get_str("geoip_dat");
    my ($server, $data, $nick, $host) = @_;
    my ($me, $nick, $user, $host) = split(" ", $data);
    my $gi = Geo::IP->open($database, GEOIP_STANDARD);
    if ($host =~ /^[0-9\.]*$/) {
        $country = $gi->country_name_by_addr($host);
    } else {
        $country = $gi->country_name_by_name($host);
    }
    $server->printformat($nick, MSGLEVEL_CRAP, 'whois_geoip', $host, $country);
}

sub cmd_geoip {
    my $country = "";
    my $database = Irssi::settings_get_str("geoip_dat");
    my $host = lc shift;
    if ($host eq "") {
        Irssi::print("USAGE: /GEOIP <host/ip>");
        return;
    }
    my $gi = Geo::IP->open($database, GEOIP_STANDARD);
    if ($host =~ /^[0-9\.]*$/) {
        $country = $gi->country_name_by_addr($host);
    } else {
        $country = $gi->country_name_by_name($host);
    }
    Irssi::print("$host is in $country");
}

Irssi::theme_register([
    'whois_geoip' => '{whois geoip %|$1}'
]);

Irssi::command_bind('geoip', \&cmd_geoip);
Irssi::signal_add_last('event 311', 'event_whois');
Irssi::settings_add_str("misc", "geoip_dat",
                                Irssi::get_irssi_dir() . "/GeoIP.dat");