#!/usr/bin/perl -w

# Copyright (C) 2009 Daniel Berteaud <daniel@firewall-services.com>

# This file is part of smeserver-zabbix-agent package.

# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Foobar; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


my $what = $ARGV[0] || '';

# On initialise nos compteurs a 0
my @results = qw(failure deferral success total);
my %cnt;
foreach (@results){
    $cnt{$_} = 0;
}

while (<STDIN>) {
    my $line = $_;

    # on limites aux lignes concernant l'envoie
    #    @400000004994ad092afa867c delivery 96906: success etc...
    next unless $line =~ m/^\@[0-9a-f]{24} delivery \d+: (success|failure|deferral).*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|CNAME_lookup_failed_temporarily)/;
    my $result = $1;
    $cnt{$result}++;
}

# Caclul des totaux:
foreach (@results){
    $cnt{total} = $cnt{total} + $cnt{$_} if $_ !~ /total/;
}

# Si l'argument est "print" on affiche toutes les stats
if ($what eq "print"){

    foreach (@results){
        print "$_: $cnt{$_}\n";
    }
}

# Si l'argument correspond a un compteur definit
# On affiche uniquemment cette valeur
elsif (defined $cnt{$what}){
    print "$cnt{$what}\n";
}

# Sinon, on quitte avec une erreur
else{
    print "supported items are: ";
    foreach (@results){
	print "$_ ";
    }
    print "\n";
    exit 1;
}
exit 0;