#!/usr/bin/perl

#
# Process incoming email for nagios user and pass arguments from Subject Line
# directly into the nagios program on the server.
#
$now = `/bin/date +%s`;
$body = "$ARGV[0]";
chomp $body;
$body =~ s/\n//g;

$author = "$ARGV[1]";
chomp $author;
$author =~ s/^ //;
$author =~ s/\"//g;
$author =~ s/</[/g;
$author =~ s/>/]/g;

$host_down = 0; #false

if ($author eq "") {
	$author = "remote";
}

open(F,">>/usr/local/nagios/procmail/logs/pm.debug.log") or die ("Can't open log file");
print F "[$now] $body\n";
 $command1 = "/usr/local/nagios/procmail/process_command.pl";
$comment = "$author--Remote Acknowledgement";
($password, $action, $crap, $crap, $crap, $crap) = split(/ /,"$body");


($foo) = $body=~/PROBLEM alert - (.*\/.*) is/;

($host, $service) = split(/\//,"$foo");

if( $body=~/Host DOWN alert for ([-\w]+)/){
  $host = $1;
  $host_down = 1; #true
}
print F "[$now] $body host=$host\n";

# Add by elik on 3/15/10, this will disable/enable notifaction used by usera for patching
if( $body =~ /(?i)usera:/ ) {

	#example mail action = "usera:hosta:on"

	@notify_fileds = split(/:/, $body);
		if ($notify_fileds[0] eq "usera") {

       			if ($notify_fileds[2] eq "off") {
               			system ("/usr/local/nagios/procmail/notifications.pl $notify_fileds[1] off");
               			system ("/usr/local/nagios/procmail/notifications.pl $notify_fileds[1] all off");
       			}

       			if ($notify_fileds[2] eq "on") {
               			system ("/usr/bin/perl /usr/local/nagios/procmail/notifications.pl $notify_fileds[1] on");
               			system ("/usr/bin/perl /usr/local/nagios/procmail/notifications.pl $notify_fileds[1] all on");
       			}
		}
}

if( $password =~ /(?i)werpoi/ ) {
	if( $action =~ /(?i)ack/  ) {
                if($host_down){
		   $output = "ACKNOWLEDGE_HOST_PROBLEM--$host--2--1--1--$comment";
                }else{
		   $output = "ACKNOWLEDGE_SVC_PROBLEM--$host--$service--2--1--1--$comment";
                }
		system("$command1 $output");
#		$output = "ADD_SVC_COMMENT--$host--$service--1--$author--$comment";
	} elsif ( $action =~ /(?i)nosvcchk/ ) {
		$output = "DISABLE_SVC_CHECK--$host--$service";
		system "'/usr/bin/perl /usr/local/nagios/procmail/process_command.pl $output'";
	} elsif ( $action =~ /(?i)nosvcnotify/ ) {
		$output = "DISABLE_SVC_NOTIFICATIONS--$host--$service";
		system "'/usr/bin/perl /usr/local/nagios/procmail/process_command.pl $output'";
	} elsif ( $action =~ /(?i)nohostchk/ ) {
		$output = "DISABLE_HOST_SVC_CHECKS--$host";
		$output2 = "DISABLE_HOST_CHECK--$host";
		system "$command1 $output";
		sleep 5; 
		system "$command1 $output2";

	}
print F "[$now] OUTPUT = $output\n";
print F "[$now] OUTPUT2 = $output2\n";
} else {
	exit 1;
}
