#!/usr/bin/perl -w
#
# Plugin to show amount of individual outgoing smtp-replies per hour
#
# Contributed by Håkon Nessjøen <lunatic@cpan.org>
#
# Magic markers - optional - used by installation scripts and
# munin-config:
#
#%# family=manual
#%# capabilities=autoconf

use strict;

my $logpath = $ENV{'logpath'} || '/usr/local/psa/var/log/';

if (exists $ARGV[0]) {
  if ($ARGV[0] eq "autoconf") {
	if (-f "${logpath}maillog") {
		print "yes\n";
	} else {
		print STDERR "no (Cannot find ${logpath}maillog. Please specify env.logpath)\n";
	}
	exit 0;
  }
}

my %responses;

#	'453' => 'You have no mail (atrn)',
#	'503' => 'Bad sequence of commands',

my %descriptions = (
	'250' => 'Mail delivery ok',
	'421' => 'Service unavail or timeout',
	'441' => 'No established connection',
	'442' => 'Connection Died',
	'450' => 'Mbox unavail or greylist',
	'451' => 'Err processing or greylist',
	'452' => 'Insufficient storage space',
	'454' => 'TLS not available now',
	'472' => 'DNS transaction timeout',
	'500' => 'Unsolicited mail',
	'501' => 'Syntax error',
	'511' => 'Blocked or blacklisted',
	'522' => 'Mailbox full',
	'550' => 'Mailbox unavailable',
	'551' => 'User not local',
	'552' => 'Content or storage error',
	'553' => 'Mailbox name not allowed',
	'554' => 'Session failed or blocked',
	'557' => 'Too many duplicate msgs'
);

#open(DATA,"cat ${logpath}maillog $logpath\@* | perl -ne'm/Remote_host_said:_(\\d+)/ && print \$1.\"\n\";' | sort | uniq -c|");
open(DATA,"grep -E '_\\(\\#4\\.4\\.1\\)|_\\(\\#4\\.4\\.2\\)|Remote_host_said:_' ${logpath}maillog | sed 's/_(\\#4\\.4\\.1)/\\/Remote_host_said:_441_/; s/_(\\#4\\.4\\.2)/\\/Remote_host_said:_442_/' | perl -ne'm/Remote_host_said:_(\\d+)/ && print \$1.\"\n\";' | sort -n | uniq -c|");
while (<DATA>) {
	if (m/\s*(\d+)\s+(\d+)/) {
		$responses{$2} = $1;
	}
}
close(DATA);


if (exists $ARGV[0]) {
  if ($ARGV[0] eq 'config') {
        print "graph_title Qmail outgoing SMTP replies\n";
        print "graph_args --base 1000 -l 0 \n";
        print "graph_vlabel replies/hour\n";
        print "graph_category mail\n";
	print "graph_total Total\n" if (keys (%descriptions) > 1);
	print "graph_info This graph shows qmail-send transaction response codes.\n";
        print "graph_order res" . join(" res", sort by_code keys %descriptions) . "\n";
	foreach (sort by_code keys %descriptions) {
		my $name = 'res' . $_;
	        print "$name.label ";
		print $_." ".$descriptions{$_}."\n";
	        print "$name.min 0\n";
	        print "$name.draw LINE1\n";
	}
        exit;
  }
}

foreach (sort by_code keys %descriptions) {
  #print "res$_.value ".int($responses{$_})."\n";
  if (exists $responses{$_}) {
	print "res$_.value $responses{$_}\n";
  }else{
	print "res$_.value 0\n";
  }
}

sub by_code {
	return $a cmp $b;
}
