#!/usr/bin/perl
# flog, a HTTPush plugin by Lluis Mora
# Logs a request using the 'old' logging -f mechanism
#
# $Id: flog,v 1.7 2001/10/28 22:13:03 jfs Exp $

use IO::Socket;
use MIME::Base64;

$|=1;

my %req;
my @kvl;


while($line=<STDIN>) {

  chomp($line);

#  print STDERR "flog: <$line>\n";

  if(! $line) {
    ProcessRequest(\%req);
    # Clean req;
    %req=undef;
    @kvl=();
  }

  if(! $req{'opcode'}) {
    if($line=~/(\w+)\s+(\d+)\.(\d+)/) {
      $req{'opcode'}=$1;
      $req{'version'}="$2.$3";
    }
  } else {
    ($key, $val) = split(":",$line,2);
    $val=MIME::Base64::decode_base64($val);
  
    if($key && $val) {
		  my %kv;
      $kv{'k'}=$key;
      $kv{'v'}=$val;

      push (@{$req{kv}}, \%kv);
    }
  }
#  print STDERR "flog: Loop\n";

}

sub ProcessRequest {
  my %req=%{shift(@_)};
  my @kvl;

#  print STDERR "flog: Processing\n";

  if($req{'opcode'} eq "identify") {
    my $plugin_name=MIME::Base64::encode_base64("flog");
    my $plugin_description=MIME::Base64::encode_base64("Logs a request using the 'old' logging -f mechanism");
    my $plugin_event=MIME::Base64::encode_base64("request");
    my $plugin_noise=MIME::Base64::encode_base64("0");

    chomp($plugin_name);
    chomp($plugin_description);
    chomp($plugin_event);
    chomp($plugin_noise);

    print "register 1.0\n";
    print "name:$plugin_name\n";
    print "description:$plugin_description\n";
    print "event:$plugin_event\n";
    print "noise:$plugin_noise\n";
    print "\n";
  } elsif($req{'opcode'} eq "request") {
    my $timestamp=time();
    my $content, $who;

    foreach $x (@{$req{'kv'}}) {
      %kv=%$x;

      if($kv{'k'} eq "sent") {
        $content=$kv{'v'};
      } elsif ($kv{'k'} eq "who") {
        $who=$kv{'v'};
      }


    }

    open(LOGFILE,">> flog.log");
    flock LOGFILE, LOCK_EX;
    print LOGFILE "_ __".$timestamp.":".$who."__\n";
    print LOGFILE "$content\n";
    flock LOGFILE, LOCK_UN;
    close(LOGFILE);

#    print "end 1.0\n\n";
#    print STDERR "ENDING\n";

  }
}
