#!/usr/bin/perl -w
# NAME: chklocal.pl
# AIM: Read a fgms log, and check if there are any LOCAL pilots
# 04/08/2012 - First cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
use Time::HiRes qw(gettimeofday tv_interval);       # provide more accurate timings
use Date::Calc qw(Week_of_Year);
use Time::gmtime;
use Time::Local;

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.1 2012-07-18";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $issue_warnings = 0;

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'C:\Users\user\Downloads\logs\fgms_curr.log';

### program variables
my @warnings = ();
my $cwd = cwd();
my $clients = 0;
my $remote = 0;
my $local = 0;
my $max_clients = 0;
my $max_remote = 0;
my $max_local = 0;
my $total_joined = 0;
my $total_expired = 0;
my $total_events = 0;
my $total_cum_time = 0;
my $total_pps = 0;

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

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

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


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

sub set_max() {
    $max_clients = $clients if ($clients > $max_clients);
    $max_remote = $remote if ($remote > $max_remote);
    $max_local = $local if ($local > $max_local);
}

sub clear_clients() {
    set_max();
    $clients = 0;
    $remote = 0;
    $local = 0;
}

sub get_time_stamp($$) {
    my ($time,$rts) = @_;
    my ($day,$mth,$yrs,$hrs,$min,$sec);
    if ($time =~ /^(\d{2})\.(\d{2})\.(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s*$/) {
        $day = $1;
        $mth = $2;
        $yrs = $3;
        $hrs = $4;
        $min = $5;
        $sec = $6;
        # my $timestamp = timegm($sec,$min,$hrd,$day,$mth-1,$yrs);
        ${$rts} = timelocal($sec,$min,$hrs,$day,$mth-1,$yrs);
        return 1;
    }
    return 0;
}


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;
    prt("Processing $lncnt lines, from [$inf]...\n");
    my ($line,$inc,$lnn);
    my ($day,$mth,$yrs,$hrs,$min,$sec);
    my ($len,$time,$info,$join,$pilot,$serv,$port,$air,$type,$left);
    my ($lastts,$ts,$elapsed,$cumtime);
    my ($packets);
    $lnn = 0;
    $lastts = 0;
    $cumtime = 0;
    $packets = 0;
    # get the FIRST time stamp
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        $len = length($line);
        if ($len < 30) {
            next;
        }
        $time = substr($line,0,19);
        if ($time =~ /^(\d{2})\.(\d{2})\.(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s*$/) {
            $day = $1;
            $mth = $2;
            $yrs = $3;
            $hrs = $4;
            $min = $5;
            $sec = $6;
            $lastts = timelocal($sec,$min,$hrs,$day,$mth-1,$yrs);
            last;
        }
    }
    # process the lines
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        $len = length($line);
        if ($len < 30) {
            prt("$lnn: UGH! WHAT IS THIS? $len [$line]\n");
            next;
        }
        $time = substr($line,0,19);
        $info = substr($line,20);
        $type = 0;
        if ($time =~ /^(\d{2})\.(\d{2})\.(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s*$/) {
            $day = $1;
            $mth = $2;
            $yrs = $3;
            $hrs = $4;
            $min = $5;
            $sec = $6;
            $ts = timelocal($sec,$min,$hrs,$day,$mth-1,$yrs);
            #              1234567890123456789
            if ($info =~ /^New REMOTE Client: /) {
                # New REMOTE Client: Isnar mpserver01:5000 (Aircraft/777-300/Models/777-300ER.xml) current clients: 1 max: 1
                $join = substr($info,19);
                ### if ($join =~ /^([-\.\s\w]+)\s+mpserver(\d{2}):(\d{4})\s+\((.+)\)\s+/) {
                if ($join =~ /^(.+)\s+mpserver(\d{2}):(\d{4})\s+\((.*)\)\s+/) {
                    $pilot = $1;
                    $serv  = $2;
                    $port  = $3;
                    $air   = $4;
                    $type = 1;
                } else {
                    prt("$lnn: join [$info] FAILED\n");
                }
            } elsif ($info =~ /^New LOCAL Client: /) {
                # 123456789012345678
                # New LOCAL Client: GA007 83.202.38.240:5000 (Aircraft/c172p/Models/c172p.xml) current clients: 27 max: 30
                $join = substr($info,18);
                ###if ($join =~ /^(.+)\s+mpserver(\d{2}):(\d{4})\s+\((.*)\)\s+/) {
                if ($join =~ /^(.+)\s+(.+):(\d+)\s+\((.*)\)\s+/) {
                    $pilot = $1;
                    $serv  = $2;
                    $port  = $3;
                    $air   = $4;
                    $type = 2;
                } else {
                    prtw("WARNING: $lnn: join [$info] FAILED\n");
                }
            } elsif ($info =~ /^TTL exceeded, dropping pilot /) {
                # 12345678901234567890123456789
                # TTL exceeded, dropping pilot BR-NVS@mpserver01  after 79 seconds.  Usage #packets in: 27 forwarded: 0 out: 0. Current clients: 18 max: 19
                $left = substr($info,29);
                if ($left =~ /^(.+)\@mpserver(\d{2})\s+after\s+(\d+)\s+seconds/) {
                    $pilot = $1;
                    $serv  = $2;
                    $sec   = $3;
                    $type = 3;
                } elsif ($left =~ /^(.+)\@LOCAL\s+after\s+(\d+)\s+seconds/) {
                    $pilot = $1;
                    $sec   = $2;
                    $type = 4;
                } else {
                    if ($issue_warnings) {
                        prtw("WARNING:$lnn: left [$left] FAILED\n");
                    } else {
                        prt("$lnn: left [$left] FAILED\n");
                    }
                }
            } else {
                if ($info =~ /^\#/) {
                    if ($info =~ /^\#\s+This\s+is\s+(.+)$/) {
                        my $sn = $1;
                    } elsif ($info =~ /Main server started!/) {
                        clear_clients() # on server start, clear all clients
                    }
                } elsif ($info =~ /Main server started!/) {
                    clear_clients() # on server start, clear all clients
                } elsif ($info =~ /^Got STAT file /) {
                    # Got STAT file /tmp/fgms_stat
                } elsif ($info =~ /^Pilots (\d+)$/) {
                    # out pilot count
                } elsif ($info =~ /^Total: Packets /) {
                    # Total: Packets 0 BL=0 INV=0 UR=0 PD=0 Telnet 0
                } elsif ($info =~ /^Since: Packets /) {
                    # Since: Packets 0 BL=0 INV=0 UR=0 PD=0 Telnet 0
                } elsif ($info =~ /^Got EXIT file : /) {
                    # Got EXIT file : /tmp/fgms_exit
                } elsif ($info =~ /^FG_SERVER::Done/) {
                    # FG_SERVER::Done() - exiting
                    clear_clients() # on EXIT, clear all clients
                } elsif ($info =~ /^Adding to blacklist: /) {
                    # [Adding to blacklist: 217.78.131.44]
                } elsif ($info =~ /^UNKNOWN RELAY: /) {
                    # [UNKNOWN RELAY: 217.78.131.44 is not a valid relay!])
                } else {
                    if ($issue_warnings) {
                        prtw("WARNING:$lnn: uncased [$info]\n");
                    } else {
                        prt("$lnn: uncased [$info]\n");
                    }
                }
            }
        } else {
            prt("$lnn: UNPROCESSED [$line]\n");
        }
        if ($type) {
            $total_events++;
            $packets++;
            if (($type == 1)||($type == 2)) {
                # JOINING PLAYER
                $total_joined++;
                $clients++;
                if ($type == 1) {
                    $remote++;
                } else {
                    $local++;
                }
            } elsif (($type == 3)||($type == 4)) {
                # EXPIRED PLAYER
                $total_expired++;
                set_max();
                $clients-- if ($clients);
                if ($type == 3) {
                    $remote-- if ($remote);
                } else {
                    $local-- if ($local);
                }
            }
            $elapsed = $ts - $lastts;
            $cumtime += $elapsed;
            if ($cumtime >= 60) {
                # per minutes stats
                my $pps = $packets / $cumtime;
                $total_pps = $pps if ($pps > $total_pps);
                $cumtime = 0;
                $packets = 0;
            }
            $total_cum_time += $elapsed;
            $lastts = $ts;
        }
    }
}

sub secs_to_DAYS_HHMMSS($) {
    my ($secs) = @_;
    my ($mins,$hour,$days);
    $mins = int($secs / 60);
    $secs = $secs - ($mins * 60);
    $hour = int($mins / 60);
    $mins = $mins - ($hour * 60);
    $days = int($hour / 24);
    $hour = $hour - ($days * 24);
    my $tm = sprintf("%3d %02d:%02d:%02d",$days, $hour, $mins, $secs);
    return $tm;
}


sub show_stats() {
    prt("Log covers ".secs_to_DAYS_HHMMSS($total_cum_time).". Max rate seen was $total_pps packets per second.\n");
    prt("Runtime : Total $total_events packets, $total_joined joined, $total_expired expired\n");
    prt("File end: $clients pilots, $remote remote, $local local\n");
    prt("Maximums: $max_clients pilots, $max_remote remote, $max_local local\n");
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_file($in_file);
show_stats();
pgm_exit(0,"");
########################################

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);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
        prt("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");
    }
}

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

# eof - template.pl
