#!/usr/bin/perl  

# Check for tmap update errrors.
# requires errors email alias

#########################
# Standard Declarations #
#########################
use POSIX;
use Env;

use Getopt::Long;      # Used for parsing runstring options
use English;
use Carp;
use Cwd;
use File::Path;
use File::Glob;
use File::Copy;

############################
# Declare Global Variables #
############################
my $sysOS;          # Operating System
my $sysHostname;    # Hostname
my $sysRelease;     # OS Release
my $sysVersion;     # OS Version
my $sysMachine;     # Architecture
($sysOS, $sysHostname, $sysRelease, $sysVersion, $sysMachine) = POSIX::uname();

# date 
my ($sys_day,$sys_mon,$sys_year) = (localtime)[3,4,5];
    $sys_mon += 1;  #jan is 0
    $sys_year += 1900;
    $today = sprintf "%d-%02d-%d",$sys_year,$sys_mon,$sys_day;  # date needs to match 2009-09-11 

my @filelist = ();
my @arr = ();
$DestPath = "/tmp/ga";        #tmp dir to hold errors
my $ERRORS = "tmap.errors";  
open(ERRORS, ">$DestPath/$ERRORS");

#create working directory
if (! -d $DestPath){
     mkpath($DestPath) or die "Failed to create $DestPath: $!\n";
     qx [chmod 777 $DestPath];  #to fix 755 permissions
}

# Test 1.  Look for trunkmap directory.  
#
if (! -d "/opt/AgilentNGN/customer/cron/trunkmap"){
        printf ERRORS "--No cron/trunkmap directory\n";
        exit;    #Anything placed after exit will not execute.  Used to  stop a script if a condition is met.
}


# Test 2.  Look for today's date on incomming files
#
   chdir("/opt/AgilentNGN/customer/cron/trunkmap/incoming");
   @filelist = <*>;     # all real files
   foreach my $file (@filelist) {
        my $line = qx[ls --full-time $file];
           $line =~ s/\s+/ /g ;
        my @arr = split(/ /,$line);
#-rwxrwxrwx 1 agilent agilent   19460 2009-09-11 01:59:46.000000000 -0500 FTW_905_DT_c7rteset

        if ($arr[5] ne "$today"){      
             printf ERRORS "--incoming/%-22s timestamp of %10s is not $today\n",$arr[8], $arr[5] ;
        } 
   }

#Test 3. At least 3 incoming files 
#
     chdir("/opt/AgilentNGN/customer/cron/trunkmap/incoming");
     chomp ($filescount = qx[ls -A | wc -l]);  
     if ($filescount < 3){
           printf ERRORS "--customer/cron/trunkmap/incoming has < 3 files\n"  ;
     }

# Test 4. Check that a dbm/trunkmap directory was created today.
# If it doesn't exist, don't even bother with rest of tests
#
   chdir("/opt/AgilentNGN/dbm/trunkmap");
   my $LastDir = qx[cd /opt/AgilentNGN/dbm/trunkmap; ls -rt | tail -1];
   my $line = qx[ls -d --full-time $LastDir];
   $line =~ s/\s+/ /g ;
    my @arr = split(/ /,$line);

#  drwxr-xr-x 2 agilent agilent 4096 2009-09-11 04:00:05.000000000 -0500 090911_040002
     if ($arr[5] !~ /$today/){
          printf ERRORS "--dbm/trunkmap/%-22s timestamp of %10s is not $today\n",$arr[8], $arr[5] ;
          exit;    #Anything placed after exit will not execute.  Used to  stop a script if a condition is met.

     } else { # perform rest of tests on files in latest dir

           # Get type of server. 
           my $ServerType = qx[/opt/AgilentNGN/bin/get_ngn_version | grep Server];
           $ServerType =~ s/Server:\s+//g;

           my $CurrentDir = $arr[8];
           chdir("$CurrentDir");

           #Test 4a. ServerType=NGN=SSC.  Should be 9 files created 
           chomp (my $filescount = qx[ls -A | wc -l]);  
           if ($ServerType eq "NGN") {
                if ($filescount < 8){
                    printf ERRORS "--trunkmap/$CurrentDir/ has < 8 files\n" ;
                }
           }

           #Test 4b. ServerType=SCE.  Should be 3 files created 
           if ($ServerType eq "SCE") {
                if ($filescount < 3){
                    printf ERRORS "--trunkmap/$CurrentDir/ has < 3 files\n" ;
                }
           }

           # Test 4c.  Check size of trunkmap.csv
           #
           my $line = qx[ls -d --full-time trunkmap.csv];
           $line =~ s/\s+/ /g ;
           my @arr = split(/ /,$line);
     
           if ($arr[4] < 100){   # size
             printf ERRORS  "--trunkmap/$CurrentDir/trunkmap.csv has size of $arr[4]\n" ;
           }

           # Test 4d.  Check trunknameCache.xml exists 
           if(! -e "trunknameCache.xml") {
                printf ERRORS  "--trunkmap/$CurrentDir/trunknameCache.xml is missing\n" ;

           } else {

                # Test 4e.  Check trunknameCache.xml size is > 300
                my $line = qx[ls -d --full-time trunknameCache.xml];
                $line =~ s/\s+/ /g ;
                my @arr = split(/ /,$line);
     
                if ($arr[4] < 300){   #size
                  printf ERRORS  "--trunkmap/$CurrentDir/trunknameCache.xml has size of $arr[4]\n" ;
                }

                # Test 4f.  Check trunknameCache.xml was created today
                if ($arr[5] !~ /$today/){
                     printf  "trunkmap/$CurrentDir/trunknameCache.xml timestamp of %10s is not $today\n", $arr[5] ;
                }

                # Test 4g.  Check size of trunknameCache.xml has changed in past 14 days
                my $DaystoCheck = 14;   # how many days to see if size has not changed
                my @LastFiles = ();     # array of last $DaystoCheck trunknameCache.xml files
                my @LastSizes = ();     # array of last $DaystoCheck trunknameCache.xml file sizes

                chdir("/opt/AgilentNGN/dbm/trunkmap");
                my @LastFiles = qx[find . -name  trunknameCache.xml -exec ls --full-time {} \\; \| tail -$DaystoCheck ];  

#-rw-r--r-- 1 agilent agilent 5089370 2009-09-13 04:00:05.000000000 -0500 ./090913_040002/trunknameCache.xml
#-rw-r--r-- 1 agilent agilent 5089370 2009-09-14 04:00:05.000000000 -0500 ./090914_040002/trunknameCache.xml

                foreach my $line (@LastFiles){
                     $line =~ s/\s+/ /g ;
                     my @arr = split(/ /,$line);
                     push (@LastSizes,$arr[4]);   # put all x number of sizes into an array
                }
# debug          print "size of last sizes: " . @LastSizes . "\n";

                #extract unique sizes (if size has not changed, will only wind up with one size)
                undef %saw;
                @unique = grep(!$saw{$_}++, @LastSizes );
# debug           print "size of unique: " . @unique . "\n";

                if (@unique lt 2 ){ # if size has not changed, will only wind up with one size)
                     printf ERRORS  "--dbm/trunknameCache.xml size of $arr[4] has not changed in past $DaystoCheck days\n" ;
                }
          } #trunknameCache.xml exists
     }

# Test 5. If /data/cron/update_tmap.log has size > 0, capture contents of log
#
   my $filesize = -s '/data/cron/update_tmap.log';
   if ($filesize > 0) {
  
       # File had errors.  Cat logfile to errors file.
       open(IN, "</data/cron/update_tmap.log");
       print ERRORS "\n--     /data/cron/update_tmap.log had size > 0\n";

       while(<IN>) { 
          print ERRORS "$_";
       }
       close(IN);
       print ERRORS ".\n";
   }
# Test 6. If size of $DestPath/$ERRORS (/tmp/wm/tmap.errors) > 0, email it 
#
   close(ERRORS);       #close so stats can be computed

   my $filesize = -s "$DestPath/$ERRORS";
   if ($filesize > 0) {
 
       # File had errors.  Cat logfile to errors file.
#       qx [cat '$DestPath/$ERRORS' | /usr/bin/mailx -s "$sysHostname trunkmap errors found on $today" wmetzger1\@hotmail.com, wmetzger1\@gmail.com];
       qx [/usr/bin/mailx -s "trunkmap errors found on $sysHostname   $today" errors < '$DestPath/$ERRORS' ];

       #cleanup
       unlink("$DestPath/$ERRORS");
   }


