#!/home/mschilli/PERL/bin/perl -w
###########################################
# boom-sender
# Mike Schilli, 2008 (m@perlmeister.com)
###########################################
use strict;
use POE;
use POE::Wheel::FollowTail;
use POE::Component::Client::TCP;
use ApacheLog::Parser 
                    qw(parse_line_to_hash);
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($DEBUG);

POE::Component::Client::TCP->new(
  Alias         => 'boom',
  RemoteAddress => 'localhost',
  RemotePort    => 8080,
  ServerInput   => sub {
      DEBUG "Server says: $_[ARG0]";
  },
  InlineStates => {
    send => sub { 
      DEBUG "Sending [$_[ARG0]] to server";
      $_[HEAP]->{server}->put($_[ARG0]);
    },
  },
  ConnectError => sub {
      LOGDIE "Cannot connect to server";
  }
); 

POE::Session->create(
  inline_states => {
    _start => sub {
      $_[HEAP]->{tail} = 
        POE::Wheel::FollowTail->new(
          Filename => 
            "/var/log/apache2/access.log",
          InputEvent => "got_log_line",
          ResetEvent => "got_log_rollover",
      );
    },
    got_log_line => sub {
      my %fields = 
               parse_line_to_hash $_[ARG0];
      my $file = $fields{ file };
      if(my $sound = file2sound($file)) {
        POE::Kernel->post("boom", "send", 
             $sound);
      }
    },
    got_log_rollover => sub {
      DEBUG "Log rolled over.";
    },
  }
);

POE::Kernel->run();
exit;

###########################################
sub file2sound {
###########################################
    $_ = $_[0];

    DEBUG "Got $_";

    s#/$#/index.html#;

    m#/index.html$# and
        return "article-page.wav";

    m#/posting.php# and 
        return "forum-post.wav";

    m#/viewforum.php# and 
        return "forum-page.wav";

    m#/images/.*html# and 
        return "image.wav";

    return "";
}
