#! /usr/bin/perl

# Scripted by: Levi Stanley & Don Lewis
#
# Date: 2006.11.03
#
# Description:  Little script to check the number of messages in a POP3 mailbox, added a warning level as well
#
# May 2007: Special thanks to Philipp Steixner for the fix for properly handling output response when# there are no messages in the INBOX.

use Net::POP3;
use Getopt::Std;
use strict;

my %options=();
getopts("c:w:h:u:p:", \%options);

if (scalar(keys(%options))<4 || !exists($options{'c'}) || $options{'w'} > $options{'c'}){
	print "usage: $0 -u username -p password -h hostname [-w warning_level] -c critical\n";
	print "\n      - Note: critical is always greater than warning_level\n";
	exit 3; # This will register as unknown in nagios
}
	
my $exit_value = 0;
my $pop = Net::POP3->new($options{'h'}, 'Timeout' => 60);
my $return_val = $pop->login($options{'u'}, $options{'p'});
if ($return_val == 0){
	print "OK: currently no messages stored on server.\r\n";
} elsif ($return_val > 0){
	my $ref_message_list = $pop->list();
	my $number_of_messages = scalar(keys(%$ref_message_list));

	if ($number_of_messages > $options{'c'}){
		print "Critical: Number of emails in system is over [$options{'c'}] -> [$number_of_messages]\r\n";
		$exit_value=2;
	} elsif (exists($options{'w'}) && $number_of_messages > $options{'w'}){
		print "Warning: Number of emails within your warning section [$options{'w'}] -> [$number_of_messages]\r\n";
		$exit_value=1;
	} else {
		print "OK: your email limit of [$options{'c'}] -> [$number_of_messages]\r\n";
	}
} else {	
	print "Error: was unable to connect to POP account.\r\n";
	$exit_value = 3;
}

$pop->quit;
exit $exit_value;
