#!/usr/bin/perl

#############################################################################################
# Author : Anthony LAPEYRE
# email : anthony.lapeyre@sfr.fr
# Name : check_zimbra_mailboxquota.pl
# Version : 1.4
# Object : Check mailbox quota for zimbra in Nagios
# USAGE : check_zimbra_mailboxquota.pl ARG0 ARG1
#             - ARG0 : Value WARNING
#             - ARG1 : Value CRITICAL
# Example : check_zimbra_mailboxquota.pl 90 95
#############################################################################################

use strict;
use Getopt::Long;

#####START VARIABLES#####
my $command = '/opt/zimbra/bin/zmprov gqu localhost';
my $warning = $ARGV[0]; # Define threshold for warning alert in %
my $critical = $ARGV[1]; # Define threshold for critical alert in %
my $code=0;
my ($account, $quota, $used, $forget, $value, $accountw, $accountc, $codeForget);
my $countwarn = 0;
my $countcrit = 0;
my @result;
#####END VARIABLES#####

@result = `$command`;

if (($warning == "") || ($critical == "")) {
        $forget = "ERROR COMMAND LINE
USAGE : ./check_zimbra_mailboxquota.pl ARG0 ARG1
     - ARG0 : Value WARNING
     - ARG1 : Value CRITICAL
Example : check_zimbra_mailboxquota.pl 90 95";
        $codeForget = 2;
        print "$forget\n";
        exit ($codeForget);
}

foreach (@result) {
        ($account, $quota, $used) = split(/ /,$_);
        if ($quota == 0) { $quota = 536870912; } # solve the problem with system accounts quota's problems like spam
 filter
                $used = ($used / $quota) *100;
        if ($used >= $critical) {
                $countcrit ++;
                $accountc="$accountc - $account";
                $code = 2;
        }

        if (($used >= $warning) && ($used < $critical)) {
                $countwarn ++;
                $accountw="$accountw - $account";
                if ($code < 2) { $code = 1; }
        }

}

if ($code == 0) { $value = "OK : No users exceed the WARNING quota : $warning% or CRITICAL : $critical%"; }
if ($code == 1) { $value = "WARNING : $countwarn users ($accountw) exceed the mailbox quota of $warning%"; }
if ($code == 2) { $value = "CRITICAL : $countcrit users ($accountc) exceed the mailbox quota of $critical% - WARNING
 : $countwarn users ($accountw) exceed the mailbox quota of $warning%"; }

print "$value\n";
exit($code);
