#!/usr/bin/perl
#
# This Perl script reads Allstar Archive files and extracts RX data to
# a separate file with node QTH and location for viewing. It uses
# Perl File:Tail to read the current archive file based on date. It
# automatically handles date changes and will switch to the next
# days file at date change. The data is stored in a file called
# rxlog.txt which is then read by a script rxlog.sh
#
# D. Crompton WA3DSP 6/2014
#
use File::Tail;
use List::Util 'first';
my $allstardb = "/var/www/html/allmon/astdb.txt";

my ($var1,$var2,$var3,$var4,$var5,$var6);
open (ASTDB,$allstardb);
my @list = <ASTDB>;

open my $out_file, '>>', '/var/log/asterisk/audio/27225/rxlog.txt' or die "$!";
$| = 1;

(my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime();
#printf("%02d/%02d/%4d %02d:%02d:%02d\n", $mon+1,$mday,$year+1900,$hour, $min, $sec);
my $current_date_file = sprintf("%s%4d%02d%02d.txt","/var/log/asterisk/audio/27225/",$year+1900,$mon+1,$mday);

# print $current_date_file;
# exit;

my $file = File::Tail->new(name=>$current_date_file,name_changes=>\&change,maxinterval=>1,adjustafter=>500);
while (defined(my $line= $file->read)) {

if (substr($line,15,5) eq "RXKEY"){

 print (substr($line,4,2),"/",substr($line,6,2),"/",substr($line,0,4)," ",substr($line,8,2),":",substr($line,10,2),":",substr($line,12,2));
 print (" ",(substr($line,15,5))," ");

print $out_file (substr($line,4,2),"/",substr($line,6,2),"/",substr($line,0,4)," ",substr($line,8,2),":",substr($line,10,2),":",substr($line,12,2));
print $out_file (" ",(substr($line,15,5))," ");


# print (" ",(substr($line,21,5)),"\n");
$nodenum = (substr($line,21,5));
$nodenum =~ s/\n//g;

 (my $match = first { /^$nodenum\|/ } @list);
           $match =~ s/\n//g;
           @nodelist=split(/\|/, $match);
           ($var1,$var2,$var3,$var4)=@nodelist;
           if ($match=="") {
                 printf ("%-10.8s%2s%-10.8s\n",$nodenum,"  ","No info");
		 printf $out_file ("%-10.8s%2s%-10.8s\n",$nodenum,"  ","No info"); 
          } else {
                 printf ("%-8.8s%-8.8s%-20.20s%2s%-25.25s\n",$var1,$var2,$var3,"  ",($var4));
		 printf $out_file ("%-8.8s%-8.8s%-20.20s%2s%-25.25s\n",$var1,$var2,$var3,"  ",($var4));
           }

 $out_file->autoflush(1);
}
}

sub change{
(my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday,my $yday,my $isdst) = localtime();
#printf("%02d/%02d/%4d %02d:%02d:%02d\n", $mon+1,$mday,$year+1900,$hour, $min, $sec);
my $new_date_file = sprintf("%s%4d%02d%02d.txt","/var/log/asterisk/audio/27225/",$year+1900,$mon+1,$mday);
sleep 10;
return $new_date_file;
}

