#!/usr/local/bin/perl -w
###########################################
# spam2geo
# Mike Schilli, 2008 (m@perlmeister.com)
###########################################
use strict;
use LWP::UserAgent;
use URI::URL;
use List::Util qw(max min);

use IP::Country::MaxMind;
use ApacheLog::Parser 
                    qw(parse_line_to_hash);

my $gi = 
   IP::Country::MaxMind->open("GeoIP.dat");

my %by_country;

open LOG, "<access.log" or 
  die "Can't open access.log ($!)"; 

while(<LOG>) {
  chomp;
  my %fields = parse_line_to_hash $_;

    # only proceed if forum post
  next if $fields{file} !~ /posting/;

  my $country = 
        $gi->inet_atocc( $fields{client} );

  if(defined $country) {
    $by_country{ $country }++;
  }
}

close LOG;

  # Convert values to Google format
my @SYMBOLS = ("A" .. "Z", 
               "a" .. "z", 0 .. 9);

my $max = max values %by_country;
my $min = min values %by_country;

for my $country (keys %by_country) {

    my $val = $by_country{ $country };
    my $norm = ($val - $min) / 
               $max * $#SYMBOLS;

    $by_country{ $country } = $norm;
}

my $chld  = join "", keys %by_country;
my $data  = join "", values %by_country;

  # Fetch chart
my $ua = LWP::UserAgent->new();

my $uri = URI::URL->new(
     "http://chart.apis.google.com/chart");

$uri->query_form(
  cht  => "t",
  chs  => "440x220",
  chtm => "world",
  chd  => "s:$data",
    # white, yellow, red
  chco => "ffffff,f4ed28,f11414",
  chld => $chld,
    # light blue
  chf  => "bg,s,EAF7FE"
);

my $resp = $ua->get($uri);
          
  # Print image on success
if($resp->is_success()) {

  open FILE, ">file.png" or die;
  print FILE $resp->content();
  close FILE;
  system ("eog file.png");
} else {

  die $resp->request->url() . " failed\n";
}
