#!/usr/bin/env perl

=begin
Extract a complete user query history from sql log file

Usage: zcat {src}.gz | perl $0 {username} OR perl $0 {username} < {src}
=cut

use strict;
use warnings;

use Data::Dumper;

my $username = ( uc $ARGV[0] )
    or die "zcat {src}.gz | perl $0 {username} OR perl $0 {username} < {src}";

my $T = $ARGV[1]; # optional time hh:mm(:ss) # can localise to minute

if ($T) {
    my ($hr,$min,$sec) = split ':', $T;
    $sec ||= qr(\d{2});
    $T = join ':', ($hr,$min,$sec); # re-create
}

my $regex = $T
    ? qr(\[\d{2}\-\d{2}\-\d{4} $T\])
    : qr(\[\d{2}\-\d{2}\-\d{4} \d{2}:\d{2}:\d{2}\]); # warn $regex;

open my $fh, '>', "./${username}.log" or die $!;

my $active = 0;

my %h;

while (<STDIN>) { # warn $_ if  m/$regex/; next;
    $active = 0   if ( m/$regex/ and not m/$username/ ); # warn $run; # another username
    $active ||= 1 if ( m/$regex $username/ ); # warn $active; # flag to begin output
    $h{$1}++ if m/$regex (\w+)/; # user queries
    next unless $active; # print $_;
    print $fh $_; # print to output until next change of username
}

print "$_: $h{$_}\n" for sort { $h{$b} <=> $h{$a} } keys %h;

my $total = 0; $total += $h{$_} for keys %h;
print "Total queries: $total\n";

exit 0;
