#!/usr/bin/perl 
#===============================================================================
#         FILE:  ./custom_mail_alert.pl
#        USAGE:  ./custom_mail_alert.pl
#  DESCRIPTION: meant as hook called by the check_logfiles plugin to send custom mail alerts 
#
#      OPTIONS:  --sender <sender> --recpt <recpt> --subject <subject> [--display-name sender display name] [--debug-file /path/to/file]
#	   AUTHOR:	 Jess Portnoy
#      VERSION:  0.2
#      CREATED:  02/21/2011 09:27:43 AM EST
#     REVISION:  ---
#===============================================================================

# Can't use these because of the import from check_logfiles hash file :(
#use strict;
#use warnings;
use Getopt::Long;

my ($sender,$recpt,$subject,$display_name,$message,$log_file,$debug_file,$send_if_rc_gt);
GetOptions(
	"sender:s" => \$sender,
	"recpt:s" => \$recpt,
	"subject:s" => \$subject,
	"display-name:s" => \$display_name,
	"message:s" => \$message,
	"log-file:s" => \$log_file,
	"send-if-rc-gt:i" => \$send_if_rc_gt,
	"debug-file:s" => \$debug_file,
);
if (defined $debug_file){
	open MY_DEBUGGIE, ">>$debug_file";
	print MY_DEBUGGIE "$0: $sender $recpt $subject $display_name $message $log_file $send_if_rc_gt\n";
	close MY_DEBUGGIE;
}
if (!defined $sender||!defined $recpt||!defined $subject||!defined $log_file ||!defined $message){
	print "Usage: $0 --sender <sender> --recpt <recpt> --subject <subject> --message <mail body> --log-file </path/to/check_logfiles/tmp/file> [--display-name <sender display name>] [--send-if-rc-gt <1-9> ] [--debug-file </path/to/file>]\n";
	exit (-1);
}

my $display_name=$display_name||$sender;
my ($escaped_sender,$escaped_recpt)=($sender,$recpt);
# Require the file that defines the hash where the desired log entry resides:
require $log_file;
# if we have service output, send the mail.
if ((defined $state->{'servicestateid'} && defined $send_if_rc_gt) && ($state->{'servicestateid'} > $send_if_rc_gt)){
	print "$state->{'servicestateid'} was lower than $send_if_rc_gt\n";
	exit 0;
}
if ($state->{'serviceoutput'}){
	my $sendmail_msg='From: '.$display_name.' <'.$sender.'\nTo:'.$recpt.'\nSubject: '.$subject.'\n\n'.$message .'\n'.$state->{'serviceoutput'};
	system ("echo -e \"".$sendmail_msg."\"| /usr/sbin/sendmail -F '".$display_name."' -f '".$sender."' '".$recpt."'");
}
