#!/usr/bin/perl -w
########################################################
# Hardware Monitor by Larry Long - larry@djslyde.com   #
# checkhardware - 2/7 programs in checksuite v2.4      #
#                                                      #
# This greps the system's dmesg log for any errors     #
# that may be hardware related.                        #
########################################################
use strict;
use Getopt::Std;
use Net::SMTP;

# Options: -h (help) -l (log) -o (output to screen) -e (email)
my %opt;getopts('hloe:', \%opt);
usage_info() unless defined @ARGV;
usage_info() if exists $opt{h};

# Localize variables throughout the rest of the program
my($email,$host,$dmesg,@note,$notify,$logdate,$logfile,$logsnip,$script,@errors,$possibility,$subject);

# Define variables
$email = $opt{e};$email = 'root' unless defined $opt{e};
$host = `hostname`;
$logfile = "/var/log/checksuite";
$logdate = `date '+%m/%d/%Y %H:%M:%S' `;
$script = " - [checksuite] checkhardware\n";
$logsnip = "----\n";
$notify = 0;
$subject = "[checksuite] advisory - possibly hardware issues found on $host";
chomp $host;chomp $logdate;chomp $subject;

push(@note, "Errors found in system's dmesg log:\n\n");

# Are there any errors in dmesg?
@errors = ("error", "failed", "unable to load", "bad", "timed out", "call trace");

foreach $possibility (@errors)
   {
   $dmesg = `dmesg | grep -i "$possibility"`;
   chomp $dmesg;
   if($dmesg ne "")
      {
   $notify++;
   push(@note, "$dmesg\n");
      }
   }

# Define where the output goes
if($notify > 0)
   {
   log_data() if exists $opt{l};
   email_data() if exists $opt{e};
   screen_data() if exists $opt{o};
   }

# Subroutines
sub usage_info
   {
   my $usage = "
Usage: $0 [-h | -lo] [-e <email>]
Options:
-h              display this help
-l              log the output to /var/log/checksuite
-o              force output to screen
-e              e-mail the output to a specified e-mail address
Where:
<email>         e-mail address of the recipient of the notification
\n";
   die $usage;
   }

sub log_data
   {
   open(LOG, ">>$logfile") or die "Can't open logfile!\n";
   print LOG $logdate,$script,@note,$logsnip;
   close(LOG);
   }

sub screen_data
   {
   print STDERR @note;
   }

sub email_data
   {
   my $smtp = Net::SMTP->new($host);
   if(! ref($smtp))
      {
      log_die("Cannot connect to SMTP\n");
      }
   $smtp->mail($email);
   $smtp->to($email);
   $smtp->data();
   $smtp->datasend("To: " . $email . "\n");
   $smtp->datasend("From: Checksuite Notification <root\@$host>\n");
   $smtp->datasend("Return-Path: " . $email. "\n");
   $smtp->datasend("Subject: " . $subject . "\n");
   $smtp->datasend("\n");
   $smtp->datasend(@note);
   $smtp->datasend();
   $smtp->quit();
   }
