#!/usr/bin/perl

use Term::ANSIColor;

#
# Repeated paterns in the reports
#

my $DeathStar;
my $EventDate;
my $EventError;
my $EventProblem;
my $EventFix;
my $Ping;
my $Pingable;
my $PlugNumber;
my $PlugGood;
my $PlugNumber;
my $RebootStatus;
$some_file="somefile.txt";

##################################################
# Was this program called with an arguement
# Arguements can be a deathstars number, a hostname
##################################################
if ( (@ARGV >= 1 ) && ( $ARGV[0] =~ m/\w/ ) ){
  chomp ( $DeathStar="$ARGV[0]" );
  chomp ( $EventError= uc ( $ARGV[1] ) );
}

##################################################
#
# If arggument to program is 'header'
# Print the header on the document.
#
##################################################
if ( $ARGV[0] =~ m/header/  ){
  &Header();
  exit;
}

##################################################
#
# If arggument to program is 'ender'
# Print the totals for the night.
#
##################################################
if ( $ARGV[0] =~ m/ender/  ){
  &Ender();
  exit;
}

##################################################
#
# Until they enter a host
#
##################################################
if ( $DeathStar eq "" ){
  until ( $DeathStar =~ m/\d{3}/ ){
    print color("green"),"Deathstar#:\t",color("reset");
    chomp($DeathStar=<STDIN>);
  }
}
##################################################
#
# Check to see if we have rebooted this host before
# PerlCookBook recipie 8.3
#
##################################################
my @Buffer;
$line_count = 0;   # Line number in the file
open ( READ_SOME_FILE, "<$some_file" ) || die "Can't read $some_file\n";
while (<READ_SOME_FILE>){
  $line_count++;
  # Enter next block if we have seen this deathstar at least once
  if ( $_ =~ m/DEATHSTAR$DeathStar\ DEAD(\W+(.*)\W+Times)?/ ){
      # if $2 is empty, we rebooted once, so make new_numb = 2 (seond reboot)
	  if ( ! $2 ){
	      $new_numb = 2;
	  } else {
	      $new_numb=$2+1; 
	  }
	  # Construct the new header for this deathstar
	  $new_head="DEATHSTAR$DeathStar\ DEAD\ $new_numb\ Times\n ";
	  print "Changed: $new_head\n";
	  
	  # push New header on to the stack
	  push ( @Buffer, $new_head );
      
	  # Go to the next line in the file 
      next;
  }
  # Add the line to the buffer
  push ( @Buffer, $_ );  
}
close ( READ_SOME_FILE )  || die "Can't close $some_file \n";
if ( $new_numb gt 0 ){
    open ( REPORT, ">$some_file" ) || die "can't open $some_file\n";
    print REPORT @Buffer;
	close ( REPORT )|| die "Can't close $some_file\n";
    exit;
}

 # Add a note to $some_file
 # open ( READ_SOME_FILE, "<$some_file" ) || die "Can't read $some_file \n";
 # close ( READ_SOME_FILE )  || die "Can't close $some_file \n";

##################################################
#
# Grab the date for this report
#
##################################################
open (DATE, "date|") || die "Could not run date:\t$?\n";
chomp($EventDate=<DATE>);
close (DATE);
print color("green"),"Date:\t\t",color("reset"),"$EventDate\n";
print color("green"),"ERROR:\n",color("reset");

if ( ! $EventError ){
  chomp ($EventError=<STDIN>);
}

###################################################
#
# If Error is LOAD
#
###################################################
if ( $EventError =~ m/load/i ){
      $Load_High="1";
       open (LOAD, "ssh deathstar$DeathStar uptime | " ) || die "Can't ssh to ds$x:\t$?\n";  
	   while (<LOAD>) { 
	      print "$_\n";
		  $load="$_\n";
	   }
}

##################################################
#
# If Error is ROOTLOCK
#
##################################################
if ( $EventError =~ m/rootlock/i ){
  print "Who rootlocked it?\t";
  chomp ( $locker=<STDIN> );
  $lock_header="$locker rootlocked deathstar$DeathStar for errors like:\n";
  push ( @rootlock_err, $lock_header );
  
  print "What was the given error?\n";
  while (<STDIN>){ 
    push ( @rootlock_err, $_ );
  }
  $EventError="";
  foreach $line (@rootlock_err){
    $EventError="$EventError"."          $line";
  }
  $EventProblem="";
  $EventFix="";

  system (clear);
  print "-------------------------------\n",
        "DEATHSTAR$DeathStar ROOTLOCKED\n",
        "-------------------------------\n",
      color("red"),"$EventDate",color("reset"),"\n",
      "  ERROR:\n",
      color("magenta"),"    $EventError",color("reset"),"\n",
      "  PROBLEM:\n",
      color("magenta"),"    $EventProblem",color("reset"),"\n",
      "  FIX:\n",
      color("magenta"),"    $EventFix",color("reset"),"\n";
   exit;
}

#
# If Error is empty, do default
#
if ( ! $EventError ){
  ##################################################
  #
  #  Was it in nagios
  #
  ##################################################
  print "Checking nagios\n";
  open ( NAGIOS, "/home/jstile/scripts_perl/death_nagios.once.pl |" ) || die "cant run death_nagios.once.pl:\t$?\n"; 
  while (<NAGIOS>){
    if ( "$_" =~ m/$DeathStar/g )  {
      push ( @nagios, "$_" );
      print "$_";
    }
  }
  
  ##########################################
  #
  # Check for high load in nagios output. 
  #
  ##########################################
  $Load_High=0;
  foreach my $line ( @nagios ){
     if ( "$line" =~ m/LOAD/g ) {
	   $Load_High="1";
	 }
  }

  ###################################################
  #
  # If Error is no 'obasched'
  #
  ###################################################
  $Dead_Obasched=0;
  foreach my $line ( @nagios ){
	 if ( "$line" =~ m/obasched/i ){
    	$Dead_Obasched="1";
		print "!!!!!!!!!! obasched dead !!!!!!!!!!!!!!\n";
	 }
  }
  ###################################################
  #
  # If Error is no 'obaexec'
  #
  ###################################################
  $Dead_Obasched=0;
  foreach my $line ( @nagios ){
	 if ( "$line" =~ m/obaexec/i ){
    	$Dead_Obaexec="1";
		print "!!!!!!!!!! obaexec dead !!!!!!!!!!!!!!\n";
	 }
  }

  ##################################################
  #
  #  Constructing the Event Problem Line
  #
  ##################################################
  $EventError="Nagios reports:\n";
  push ( @EventErrs, "$EventError" );

  @EventErrs=( @EventErrs, @nagios );

  print "Using:\t$EventError\n";

  #
  #  Append nagios output (should probably use arrays
  #  
  foreach $line (@nagios){
    $EventError="$EventError"."          $line";
  }
}

print color("green"),"PROBLEM:\n",color("reset");
#js#chomp($EventProblem=<STDIN>);
#
# If Event is empty, do default
#
if ( ! $EventProblem ){

  #################################################
  #
  #  Was load high and Are frames hung
  #
  if ( $Load_High eq "1" ){
	   open ( OQEDUMP, "oqedump ds$DeathStar |egrep 'command|queueTime |cpuTime |realTime ' |" ) || die "cant run oqedump:\t$?\n"; 
	   while (<OQEDUMP>){
	      #
		  # Get rid of blank lines
		  #
		  if ( !("$_" =~ m/^$/g) ) {
             push ( @oqedump, "$_" ); 
             print "\t\t$_";
          }
	   }
	   close ( OQEDUMP ) || warn "can't close oqedump file handle\n";
	   print "Should I continue? (y/n)\n";
	   chomp ( $quit=<STDIN> );	
	   if ( $quit !~ m/y/g  ){
	       print "Quitting\n";
		   exit;  
	   } 
  }
  ##################################################
  #
  #  What is in dsq
  #
  print "Checking dsq:\n";
  open (DSQ, "/home/jstile/scripts_perl/dsq $DeathStar |")|| die "cant run dsq:\t$?\n"; 
  while (<DSQ>){
    #
    # Get rid of blank lines 
    #
    if ( !("$_" =~ m/^$/g) ) {
      push ( @dsq, "$_" ); 
      print "\t\t$_";
    }
  }

  ##################################################
  #
  #  Was it pingable?
  #  
  print "Checking Ping...\n";
  $pingstatus=system ("ping -c 1 ds$DeathStar >> /dev/null");
  if ( "$pingstatus" ) {
      print "It's Not Pingable!!!\n";
      $Pingable="  ping deathstar$DeathStar            \# No Response";      
  } else {
      print "It's Pingable!!!\n";
      $Pingable="  ping deathstar$DeathStar            \# Response";
  }

 # print "Pingable?\t";
 #  chomp($Ping=<STDIN>);
 #  if ( $Ping =~ m/^y(es)?$/i ){
 #      $Pingable="  ping deathstar$DeathStar            \# Response";
 #   } else {
 #       $Pingable="  ping deathstar$DeathStar           \# No Response";
 #   }
  
  ##################################################
  #
  #  Was it ssh-able?
  #
  $Sshable="ssh deathstar$DeathStar             \# No Response";
  
  ##################################################
  #
  #  Constructing the Event Problem Line
  #
  ##################################################
  if ( $Dead_Obaexec eq "1" ){
      $PRoblem="\'obaexec\' DEAD";
	  $EventProblem="Obaexec dead\n\tChecking running processes:\n";
      open ( PROCESSES, "ssh deathstar$DeathStar ps -ef | grep oba|" ) || die "Can't connect to $DeathStar:\t$!\n";
 	  while (<PROCESSES>){ 
 	  	push ( @processes, "$_" );
 	  };	  
      push ( @EventProbs, @processes );
	  foreach $line ( @EventProbs ){
	     $EventProblem="$EventProblem"."          $line";
	  } 
  } elsif ( $Dead_Obasched eq "1" ){
      $PRoblem="\'obasched\' DEAD";
	  $EventProblem="Obasched dead\n\tChecking running processes:\n";
      open ( PROCESSES, "ssh deathstar$DeathStar ps -ef | grep oba|" ) || die "Can't connect to $DeathStar:\t$!\n";
 	  while (<PROCESSES>){ 
 	  	push ( @processes, "$_" );
 	  };	  
      push ( @EventProbs, @processes );
	  foreach $line ( @EventProbs ){
	     $EventProblem="$EventProblem"."          $line";
	  } 
  } elsif ( $Load_High eq "1" ){
      $PRoblem="HIGH LOAD";
      $EventProblem="Load out of control\n\t\t$load\n\tChecking running frames:\n\t\toqedump ds$DeathStar \|egrep \'comment\|cpuTime \|realTime \'\n" ;
      push ( @EventProbs, @oqedump );
	  foreach $line ( @EventProbs ){
	     $EventProblem="$EventProblem"."          $line";
	  }
	  if ( $load =~ m/load\b+average/ ){
	     $EventProblem="$EventProblem"."          $load";
	  } 
  } else  {
      $PRoblem="DEAD";
      push ( @EventProbs, "$Pingable");
      push ( @EventProbs, "$Sshable");
      @EventProbs=(@EventProb,@dsq);

      $EventProblem="System died.\n".
         "      $Pingable\n".
         "        ssh deathstar$DeathStar             # No Response\n"
  }
  #
  #  Append dsq output (should probably use arrays
  #  
  $EventProblem="$EventProblem"."\n\tChecking SIO deathstar database\n        dsq $DeathStar                                   \n";
  foreach $line (@dsq){
    $EventProblem="$EventProblem"."          $line";
  }
}
##################################################  
#												    
#  Constructing the Event Fix Line				    
#												    
##################################################  
if ( $Dead_Obaexec eq "1" ){
   $EventFix="The only option is to reboot the deathstar\n",
              "\tReboot system $DeathStar.\n",
			  "\tSystem booted\n"; 
} elsif ( $Dead_Obasched eq "1" ){
   $EventFix="The only option is to reboot the deathstar\n",
              "\tReboot system $DeathStar.\n",
			  "\tSystem booted\n"; 
} elsif ( $Load_High eq "1" ){
   $EventFix="Ask Render Support to requeue the shots.\n",
             "      obarequeue ds$DeathStar\n",
			 "\tReboot system $DeathStar.\n",
			 "\tSystem booted\n";     
} else {
 
  #
  #  What plug was rebooted?
  #
  print "Reboot Plug Number:\t";
  chomp ($PlugNumber=<STDIN>);

  #
  #  Did the system reboot with the plug?
  #
  print "Did Plug Reboot:\t";
  chomp ($PlugGood=<STDIN>);
  if ( $PlugGood =~ m/^y(es)?$/i ){
    $RebootStatus="System came up.";
  } else {
    $RebootStatus="* BAD PLUG: deathstar$DeathStar-maint plug $PlugNumber";
  }


  #
  #  Default report for rebooted deathstar
  #
  $EventFix="Reboot system $DeathStar.\n".
            "      ssh conterm-h2\n".
            "      telnet deathstar$DeathStar-console  # System is dead\n".
            "      telnet deathstar$DeathStar-maint\n".
            "        RPC-28A> status\n".
            "        RPC-28A>reboot $PlugNumber\n\n".
            "    $RebootStatus\n";
}

system (clear);
print "------------------------------\n",
      "DEATHSTAR$DeathStar $PRoblem\n",
      "------------------------------\n",
      color("red"),"$EventDate",color("reset"),"\n",
      "  ERROR:\n",
      color("magenta"),"    $EventError",color("reset"),"\n",
      "  PROBLEM:\n",
      color("magenta"),"$EventProblem",color("reset"),"\n",
      "  FIX:\n",
      color("magenta"),"    $EventFix",color("reset"),"\n";

open ( REPORT, ">>$some_file" ) || die "can't append to $some_file\n";
print REPORT  "------------------------------\n",
      "DEATHSTAR$DeathStar $PRoblem\n",
      "------------------------------\n",
      "$EventDate\n",
      "  ERROR:\n",
      "\t$EventError\n",
      "  PROBLEM:\n",
      "\t$EventProblem\n",
      "  FIX:\n",
      "\t$EventFix\n";
close ( REPORT )|| die "Can't close $some_file\n";

#===================================
# Print the deader for the night
#===================================
sub Header (){
  use Time::Local;
  $now = timelocal($seconds, $minues, $hours, (localtime) [3,4,5] );

  # One day, 60 sec/min, 60 min/hr, 24hr/day, 1 day
  $offset = 60 * 60 * 24 * 1 ; 
  $tomorrow = $now + $offset ;

  use POSIX qw(strftime);

  open ( MAINT_ALL, "maint -a |" ) || die "can not run maint:\t $!\n";
  while (<MAINT_ALL>){
    chomp ( $_ );
	if ( ! ($_ =~ m/^The/) ){
	    push (@maint_all, "$_\n" );
      }
  }
  close ( MAINT_ALL );
  print "Report:  ", strftime("%A %B%e", localtime($now)), " -> ",strftime("%A %B%e", localtime($tomorrow)), "\n",
		"*******************************************************\n",
		"Summary Major Events\n",
		"*******************************************************\n",
		"Reboot due to: death:\n",
		"\n",	
		"*******************************************************\n",
		"Things For The Day  Crew:\n",
		"*******************************************************\n",
		"SIO - \n",
		"\n",		
		"******************************************************\n",
		"The Long Form\n",
		"******************************************************\n",
		"-------------------------------\n",
		"DEATHSTAR LINEUP AS OF ", strftime("%z", localtime($now)),  ,"\n",
		"-------------------------------\n",
		"Offline:\n",
		"------------------------------",
		@maint_all;
  open ( REPORT, ">>$some_file" ) || die "can't open $some_file\n";
  print REPORT "Report:  ", strftime("%A %B%e", localtime($now)), " -> ",strftime("%A %B%e", localtime($tomorrow)), "\n",
		"*******************************************************\n",
		"Summary Major Events\n",
		"*******************************************************\n",
		"Reboot due to: death:\n",
		"\n",	
		"*******************************************************\n",
		"Things For The Day  Crew:\n",
		"*******************************************************\n",
		"SIO - \n",
		"\n",
		"******************************************************\n",
		"The Long Form\n",
		"******************************************************\n",
		"-------------------------------\n",
		"DEATHSTAR LINEUP \n",
		"-------------------------------\n",
		"Offline:\n",
		"------------------------------",
		@maint_all;
  close ( REPORT )|| die "Can't close $some_file\n";

}
#===================================
# End of night calculations
#===================================
sub Ender (){
  open ( REPORT, "<$some_file" ) || die "can't open $some_file\n";
  while (<REPORT>){
     chomp ($_ );
	 if ( $_ =~ m/DEATHSTAR(\d+3)/ ){
	    print "$_\n";
     }
  }
  close ( REPORT )|| die "Can't close $some_file\n";
}
