#!/usr/bin/env perl

use strict;
use warnings;

#use lib '../lib';
use Getopt::Std;
use Apache::TS::BinLog;

my ( $file, $file_format );
our( $opt_f, $opt_t, $opt_l, $opt_s );

getopt('ftls');

sub VERSION_MESSAGE {
    print "$0 $Apache::TS::BinLog::VERSION (C) 2013 Yahoo! inc.\n";
}

sub HELP_MESSAGE {
    VERSION_MESSAGE();
    print <<EOT;
usage: $0 -[options] -f <filename> /path/to/squid.blog file
options:
  -t [ 'END' | <timestamp> ] start parsing from <timestamp> or from 'END' - <slice_length> ( 'END' implies -l ) 
  -l <slice_length> in seconds.
  -s <format_string> only output fields listed in the <format_string> ( "field, field, field" ) 
EOT
exit 0;
}

if ( $opt_f ) { $file = $opt_f; }
else { die "You need to give me a file to slice with -f <file>"; }

my $parser = Apache::TS::BinLog->new( 'file' => $file );

if ( $opt_l ) { $parser->set_length( $opt_l ); }

if ( $opt_t && $opt_t ne 'END' ) { $parser->set_tstamp( $opt_t ) };
if ( $opt_t && $opt_l && $opt_t eq 'END' ) { $parser->set_tstamp( $parser->get_last_tstamp() - $opt_l ); }

if ( $opt_s ) {
  my @input_fields = split( ',', $opt_s );
  my @line_fields = @{ $parser->get_line_fields() };
  my $valid = 0;
  foreach my $ifield ( @input_fields ) {
    $valid = 0;
    foreach my $lfield ( @line_fields ) {
      if ( $ifield eq $lfield ) { $valid = 1; }
    }
    last unless $valid;
  }
  if ( $valid ) {
    while ( my $line = $parser->get_line() ) {
      foreach my $ifield ( @input_fields ) {
        print $line->{ $ifield }, " ";
      }
      print "\n";
    } 
  } else { 
    print "One or more field(s) provided not found in current log file\n";
    print "Valid fields are:  ";
    foreach my $lfield ( @line_fields ) { print $lfield, " "; }
    print "\n";
    die;
  }
} else {
  while ( my $line = $parser->get_ascii_line() ) {
    print $line, "\n";
  }
}
