#!/usr/bin/perl -w
# NAME: showlog.pl 
# AIM: Read fgms log file, and enumerate pilots
# 17/06/2012 - Initial cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.2 2012-10-16";
# my $VERS = "0.0.1 2012-01-06";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_xml = '';

### program variables
my @warnings = ();
my $cwd = cwd();

# debug
my $debug_on = 0;
my $def_file = '/var/log/fgms_fgx.log';

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub prtv($) {
    my $txt = shift;
    if (VERB1()) {
        prt($txt);
    } else {
        prt_log($txt);
    }
}

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prtv( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prtv("$itm\n");
        }
        prtv("\n");
    } else {
        prtv( "\nNo warnings issued.\n\n" ) if (VERB9());
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prtv($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prtv("$tx\n");
   push(@warnings,$tx);
}

sub adj_callsign($) {
    my $rcs = shift; # = \$call_sign
    ${$rcs} .= ' ' while (length(${$rcs}) < 7);
}

sub secs_DDHHMMSS2($) {
    my ($secs) = @_;
    my ($mins,$hour,$days);
    $mins = int($secs / 60);            # get minutes (integer)
    $secs = $secs - ($mins * 60);       # fix seconds
    $hour = int($mins / 60);            # get hour (integer)
    $mins = $mins - ($hour * 60);       # fix mins
    $days = int($hour / 24);            # get days (integer)
    $hour = $hour - ($days * 24);       # fix hour
    # add a zero if less that 10
    $days = "0$days" if ($days < 10);
    $hour = "0$hour" if ($hour < 10);
    $mins = "0$mins" if ($mins < 10);
    $secs = "0$secs" if ($secs < 10);
    return "$days $hour:$mins:$secs";
}

sub secs_HHMMSS2($) {
    my ($secs) = @_;
    my ($mins,$hour);
    $mins = int($secs / 60);
    $secs = $secs - ($mins * 60);
    $hour = int($mins / 60);
    $mins = $mins - ($hour * 60);
    $hour = "0$hour" if ($hour < 10);
    $mins = "0$mins" if ($mins < 10);
    $secs = "0$secs" if ($secs < 10);
    return "$hour:$mins:$secs";
}


sub show_active($) {
    my $rh = shift;
    my $cnt = 0;
    my ($call_sign,$tsecs,$ac,$csecs,$ra);
    foreach $call_sign (keys(%{$rh})) {
         $ra = ${$rh}{$call_sign};
         if (${$ra}[2]) {
             $cnt++;
         }
    }

    if ($cnt) {
        prt("Display of $cnt active pilots...\n") if ($cnt);
        foreach $call_sign (sort keys(%{$rh})) {
            $ra = ${$rh}{$call_sign};
            if (${$ra}[2]) {
                $tsecs = ${$ra}[0];
                $ac = ${$ra}[1];
                adj_callsign(\$call_sign);
                $csecs = secs_HHMMSS2($tsecs);
                prt("$call_sign $ac\n");
            }
        }
    } else {
        prt("There appears NO active pilots...\n");
    }
}


sub process_in_file($) {
    my ($inf) = @_;
    if (! open INF, "<$inf") {
        pgm_exit(1,"ERROR: Unable to open file [$inf]\n"); 
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prtv("Processing $lncnt lines, from [$inf]...\n");
    my ($line,$inc,$lnn,$time,$info);
    $lnn = 0;
    my ($day,$mth,$yr,$hrs,$min,$sec);
    my ($cday,$cmth,$cyr,$msg);
    my ($call_sign,$serv,$port,$ac,$secs,$tsecs,$ra,$csecs1,$csecs2);
    $cday = 0;
    $cmth = 0;
    $cyr  = 0;
    my $day_cnt = 0;
    my $max_secs = 0;
    my %rem_clients = ();
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        if ($line =~ /^(\d{2}\.\d{2}\.\d{4}\s+\d{2}:\d{2}:\d{2})\s+(.+)$/) {
            $time = $1;
            $info = $2;
            if ($time =~ /^(\d{2})\.(\d{2})\.(\d{4})\s+(\d{2}):(\d{2}):(\d{2})/) {
                $day = $1;
                $mth = $2;
                $yr  = $3;
                $hrs = $4;
                $min = $5;
                $sec = $6;
                if (($cday != $day)||($cmth != $mth)||($cyr != $yr)) {
                    $cday = $day;
                    $cmth = $mth;
                    $cyr  = $yr;
                    if ($day_cnt) {

                    }
                    prtv("$time $day_cnt\n");
                    $day_cnt = 1;
                } else {
                    $day_cnt++; # same day
                }

            }
            if ($info =~ /^New REMOTE Client:\s+(.+)\s+mpserver(\d{2}):(\d{4})\s+\((.+)\)/) {
                # New REMOTE Client: BR-RIC mpserver01:5000 (Aircraft/737-300/Models/737-300.xml)
                $call_sign = $1;
                $serv = $2;
                $port = $3;
                $ac   = $4;
                if (!defined $rem_clients{$call_sign}) {
                    $rem_clients{$call_sign} = [0, $ac, 1];
                    adj_callsign(\$call_sign);
                    prtv("$call_sign serv $serv:$port [$ac]\n");
                }
            # } elsif ($info =~ /^TTL exceeded, dropping pilot (.+)\@mpserver(\d{2})\safter\s+(\d+)\s+seconds/) {
            } elsif ($info =~ /^TTL exceeded, dropping pilot /) {
                if ($info =~ /^TTL exceeded, dropping pilot (.+)\@mpserver(\d{2})\s+after\s+(\d+)\s+seconds/) {
                    $call_sign = $1;
                    $serv = $2;
                    $secs = $3;
                    if (defined $rem_clients{$call_sign}) {
                        $ra = $rem_clients{$call_sign};
                        ${$ra}[2] = 0;      # set as DROPPED
                        ${$ra}[0] += $secs; # accumulate seconds
                        $tsecs = ${$ra}[0]; # get total seconds
                        if ($tsecs > $max_secs) {
                            $max_secs = $tsecs;
                            adj_callsign(\$call_sign);
                            $csecs1 = secs_HHMMSS2($secs);
                            $csecs2 = secs_DDHHMMSS2($tsecs);
                            prtv("$call_sign dropped after $csecs1 $csecs2\n");
                        }
                    }
                } else {
                }
                # .  Usage #packets in: 1 forwarded: 0 out: 0./) {
            }
            #prtv("$time\n");
        }
    }
    show_active(\%rem_clients);
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_file($in_file);
pgm_exit(0,"");
########################################
sub give_help {
    prtv("$pgmname: version $VERS\n");
    prtv("Usage: $pgmname [options] in-file\n");
    prtv("Options:\n");
    prtv(" --help  (-h or -?) = This help, and exit 0.\n");
    prtv(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prtv(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prtv(" --out <file>  (-o) = Write output to this file.\n");
}

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prtv("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prtv("Set to load log at end.\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_xml = $sarg;
                prtv("Set out file to [$out_xml].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prtv("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
        prtv("Set DEFAULT input to [$in_file]\n");
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if (! -f $in_file) {
        pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    }
}

# eof - showlog.pl
