#!/usr/bin/perl

use strict;
use Parse::Syslog;
use Socket;
use IO::Socket;

use Geo::IP;
my $gi = Geo::IP->open("GeoLiteCity.dat", GEOIP_STANDARD);

my $server = IO::Socket::INET->new(
  Proto     => 'tcp',
  LocalPort => 10000,
  Listen    => 5,
  Reuse     => 1 )
or die "can't setup server";

my $num_of_client = -1;

while (1) {
  my $client;
  do {
    $client = $server->accept;
  } until ( defined($client) );
  my $peerhost = $client->peerhost();
  print "Accepted a client $client, $peerhost, id = ", ++$num_of_client, "\n";
  $client->autoflush(1);
  open (SYSLOG, "/tmp/perl.pipe");
  while(<SYSLOG>) {
    my @messages = split(",", $_);
  
    my $host = substr($messages[0],1);
    my $facility = substr($messages[1],1);
    my $priority = substr($messages[2],1);
    my $level = substr($messages[3],1);
    my $tag = substr($messages[4],1);
    my $YMD = substr($messages[5],1);
    my $HMS = substr($messages[6],1);
    my $program = substr($messages[7],1);
    my $msg = substr($messages[8],1);
    if($msg =~/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ){
      my $ip = $1;
      if (unpack('N',inet_aton($ip)) > 0) {
        my $record = $gi->record_by_addr($ip);
        if ($record) {
          print "Sending $ip ".$record->latitude.":".$record->longitude."\n";
	  print $client $record->latitude.":".$record->longitude."\n";
        }
      } else {
        print "$msg $ip Hrrm no country for old men.\n";
      }
    } else {
      print "No ip in $msg";
    }
  }
}
