#! /usr/bin/perl -w
################################################################################
# Copyright 2004-2013 MERETHIS
# Centreon is developped by : Julien Mathis and Romain Le Merlus under
# GPL Licence 2.0.
# 
# This program 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.
# 
# This program 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 
# this program; if not, see <http://www.gnu.org/licenses>.
# 
# Linking this program statically or dynamically with other modules is making a 
# combined work based on this program. Thus, the terms and conditions of the GNU 
# General Public License cover the whole combination.
# 
# As a special exception, the copyright holders of this program give MERETHIS 
# permission to link this program with independent modules to produce an executable, 
# regardless of the license terms of these independent modules, and to copy and 
# distribute the resulting executable under terms of MERETHIS choice, provided that 
# MERETHIS also meet, for each linked independent module, the terms  and conditions 
# of the license of that module. An independent module is a module which is not 
# derived from this program. If you modify this program, you may extend this 
# exception to your version of the program, but you are not obliged to do so. If you
# do not wish to do so, delete this exception statement from your version.
# 
# For more information : contact@centreon.com
# 
# SVN : $URL$
# SVN : $Id$
#
#####################################################################################
#
# Script init
#

use strict;
require "/DBA/nagios/nagios-plugins/1.latest/plugins/Centreon/SNMP/Utils.pm";

use vars qw($PROGNAME);
use Getopt::Long;
use vars qw($opt_V $opt_t $opt_h $opt_f $opt_d $opt_n $opt_w $opt_c $opt_s $opt_L $opt_M $opt_a @test);

my %ERRORS = ('OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3);

my %centreon = Centreon::SNMP::Utils::load_oids($ERRORS{'UNKNOWN'}, "/DBA/nagios/nagios-plugins/1.latest/plugins/centreon.conf");

# Plugin var init

my ($hrStorageDescr, $hrStorageAllocationUnits, $hrStorageSize, $hrStorageUsed, $hrStorageLabel);
my ($AllocationUnits, $Size, $Used);
my ($tot, $used, $pourcent, $return_code);

$PROGNAME = "$0";
sub print_help ();
sub print_usage ();

my %OPTION = (
    "host" => undef,
    "snmp-community" => "public", "snmp-version" => 1, "snmp-port" => 161, 
    "snmp-auth-key" => undef, "snmp-auth-user" => undef, "snmp-auth-password" => undef, "snmp-auth-protocol" => "MD5",
    "snmp-priv-key" => undef, "snmp-priv-password" => undef, "snmp-priv-protocol" => "DES",
    "maxrepetitions" => undef, "snmptimeout" => undef,
    "64-bits" => undef,
);

Getopt::Long::Configure('bundling');
GetOptions
    (
    "H|hostname|host=s"         => \$OPTION{'host'},
    "C|community=s"             => \$OPTION{'snmp-community'},
    "v|snmp|snmp-version=s"     => \$OPTION{'snmp-version'},
    "P|snmpport|snmp-port=i"    => \$OPTION{'snmp-port'},
    "u|username=s"              => \$OPTION{'snmp-auth-user'},
    "p|authpassword|password=s" => \$OPTION{'snmp-auth-password'},
    "k|authkey=s"               => \$OPTION{'snmp-auth-key'},
    "authprotocol=s"            => \$OPTION{'snmp-auth-protocol'},
    "privpassword=s"            => \$OPTION{'snmp-priv-password'},
    "privkey=s"                 => \$OPTION{'snmp-priv-key'},
    "privprotocol=s"            => \$OPTION{'snmp-priv-protocol'},
    "maxrepetitions=s"          => \$OPTION{'maxrepetitions'},
    "snmp-timeout=i"            => \$OPTION{'snmptimeout'},
    "64-bits"                   => \$OPTION{'64-bits'},

    "h"   => \$opt_h, "help"         => \$opt_h,
    "V"   => \$opt_V, "version"      => \$opt_V,
    "s"   => \$opt_s, "show"         => \$opt_s,
    "d=s" => \$opt_d, "disk=s"       => \$opt_d,
    "n"   => \$opt_n, "name"         => \$opt_n,
    "w=s" => \$opt_w, "warning=s"    => \$opt_w,
    "c=s" => \$opt_c, "critical=s"   => \$opt_c,
    "L"   => \$opt_L, "label"        => \$opt_L,
    "a=s" => \$opt_a, "cache=s"    => \$opt_a,
    "M"   => \$opt_M, 
    "t=s" => \$opt_t);

if ($opt_V) {
    print_revision($PROGNAME,'$Revision: 1.3 $');
    exit $ERRORS{'OK'};
}
if ($opt_h) {
    print_help();
    exit $ERRORS{'OK'};
}

my $partition = 0;
if (!defined($opt_s)) {
    if (!defined($opt_d)) {
        print "Option -d (--disk) needed\n";
        exit $ERRORS{'UNKNOWN'};
    }
    if ($opt_d =~ /([0-9]+)/ && !defined($opt_n)) {
        $partition = $1;
    } elsif (!$opt_n){
        print "Unknown -d: number expected... try another disk - number\n";
        exit $ERRORS{'UNKNOWN'};
    }
    if (defined($opt_n) && !defined($opt_d)) {
        print "Option -n (--name) need option -d (--disk)\n";
        exit $ERRORS{'UNKNOWN'};
    }
}

$opt_a = 3 if (!$opt_a);

if (!$opt_c) {
    $opt_c = 95;
}
if (!$opt_w) {
    $opt_w = 90;
}

# this are boolean variables to see if --warn or --crit were set in MB/GB
# --warn and --crit values will be stored in $warning and $critical variables
# if they are set in GB they are converted to MB 
my $criticalMB = 0;
my $warningMB = 0;

my $critical = 95;
if ($opt_c && $opt_c =~ /^[0-9]+$/) {
    $critical = $opt_c;
}
if ($opt_c && $opt_c =~ /^([0-9]+)(.)[Bb]$/) {
    $criticalMB = 1;
    $critical = $1;
    ($critical = $critical * 1024) if $2 =~ /[Gg]/ ;
}

my $warning = 90;
if ($opt_w && $opt_w =~ /^[0-9]+$/) {
    $warning = $opt_w;
}
if ($opt_w && $opt_w =~ /^([0-9]+)(.)[Bb]$/) {
    $warningMB = 1;
    $warning = $1;
    ($warning = $warning * 1024) if $2 =~ /[Gg]/ ;
}

# If one of the warning/critical thresholds is set in MB/GB and the other in percent the check will fail
# if both are percent or storage size the check will be performed in different ways
# percent applies to used space so --crit must be higher than --warn
# MB applies to free space so --crit must be lower than --warn
if ($criticalMB == $warningMB) {
    if ($criticalMB && ($critical >= $warning)) {
        print "(--crit) must be inferior to (--warn) when using absolute size";
        print_usage();
        exit $ERRORS{'OK'};
    } 
    if (!$criticalMB && ($critical <= $warning)) {
        print "(--crit) must be superior to (--warn)";
        print_usage();
        exit $ERRORS{'OK'};
    }
} else {
    print "(--crit) and (--warn) must both use either percent or absolute sizes";
    print_usage();
    exit $ERRORS{'OK'};
}

my $name = $0;
$name =~ s/\.pl.*//g;

# Plugin snmp requests
my $OID_hrStorageDescr = "";
if (defined($opt_t) && ($opt_t eq "AIX" || $opt_t eq "AS400")) {
    $OID_hrStorageDescr = ".1.3.6.1.2.1.25.3.8.1.2";
} else {
    $OID_hrStorageDescr = $centreon{MIB2}{HR_STORAGE_DESCR};
}
my $OID_hrStorageAllocationUnits = $centreon{MIB2}{HR_STORAGE_ALLOCATION_UNITS};
my $OID_hrStorageSize = $centreon{MIB2}{HR_STORAGE_SIZE};
my $OID_hrStorageUsed = $centreon{MIB2}{HR_STORAGE_USED};

my ($session_params) = Centreon::SNMP::Utils::check_snmp_options($ERRORS{'UNKNOWN'}, \%OPTION);
my $session = Centreon::SNMP::Utils::connection($ERRORS{'UNKNOWN'}, $session_params);

my $cacheFile = "/DBA/centreon-data/centreon-plugins/tmp/remote_storage_cache_" . $OPTION{'host'};
my $result;
my $mustCreateFile = 0;
my $row;
my $countLine;

#
# Cache File exists, lets read it
#
if (-e $cacheFile) {
    my $one_line = 0;
    open(FILE,"<".$cacheFile);
    $row = <FILE>;
    if (defined($row)) {
        chomp $row;
        my $deltaTime = time() - $row;
        if ($deltaTime > ($opt_a * 3600)) {
            $mustCreateFile = 1;
        }
        $one_line = 1 if (!<FILE>);
    }
    close(FILE);
    
    # Manage file empty or line 1 empty
    if (!defined($row) || $row eq '' || $one_line == 1) {
        $mustCreateFile = 1;
    }
} else {
    $mustCreateFile = 1;
}

if ($mustCreateFile) {
    $result = Centreon::SNMP::Utils::get_snmp_table($OID_hrStorageDescr, $session, $ERRORS{'UNKNOWN'}, \%OPTION);
    unless (open(FILE,">".$cacheFile)){
        print "Check mod for temporary file : ".$cacheFile."...\n";
        exit $ERRORS{"UNKNOWN"};
    }
    my $currentTime = time();
    my $first = 0;
    foreach my $key (oid_lex_sort(keys %$result)) {
        if (defined($opt_t) && $opt_t eq "AS400"){
            $result->{$key} =~ s/\ //g;
        }        
        my @oid_list = split (/\./,$key);
        my $partitionIndex = pop (@oid_list);
        if ($first == 0) {
            print FILE $currentTime."\n";
            $first = 1;
        }
        print FILE $partitionIndex.";".$result->{$key}."\n";
    }
    close(FILE);
}


#getting partition using its name instead of its oid index
if ($opt_n) {    
    if (!-e $cacheFile) {
        printf("ERROR: Could not open " . $cacheFile);        
        exit $ERRORS{'UNKNOWN'};
    }

    my $expr = "";
    my $case_sensitive = 1;
    if ($opt_d =~ m/^[A-Za-z]:/i) {
        $opt_d =~ s/\\/\\\\/g;
        $expr = "^$opt_d";
    } elsif ($opt_d =~ m/^\//) {
        $expr = "^$opt_d\$";
    } else {
        $case_sensitive = 0;
        $expr = "$opt_d";
    }
    
    open(FILE,"<".$cacheFile);
    $countLine = 0;
    while ($row = <FILE>){
        chomp $row;
        if ($countLine) {
            my @resLine = split(/\;/, $row);
            if ($case_sensitive == 1 && $resLine[1] =~ /$expr/) {
                $partition = $resLine[0];
            } elsif ($case_sensitive == 0 && $resLine[1] =~ /$expr/i) {
                $partition = $resLine[0];
            }
        }
        $countLine++;
    }
    close(FILE);    
}

if ($opt_s) {
    if (!-e $cacheFile) {
        printf("ERROR: Could not open " . $cacheFile);        
        exit $ERRORS{'UNKNOWN'};
    }

    open(FILE,"<".$cacheFile);
    $countLine = 0;
    while ($row = <FILE>){
        if ($countLine) {
            my @resLine = split(/\;/, $row);
            print "hrStorage ".$resLine[0]." :: ".$resLine[1];
        }
        $countLine++;
    }
    close(FILE);
    exit $ERRORS{'OK'};
}


$result = Centreon::SNMP::Utils::get_snmp_leef([$OID_hrStorageDescr.".".$partition,
                                                $OID_hrStorageAllocationUnits.".".$partition,
                                                $OID_hrStorageSize.".".$partition,
                                                $OID_hrStorageUsed.".".$partition
                                                ], $session, $ERRORS{'UNKNOWN'},
                                                defined($opt_n) ? " Cases: 1) SNMP not working. 2) specify the disk name when option -n is used. 3) Disk not exist. 4) Delete cache file '$cacheFile' (maybe corrupted)" : undef);

$hrStorageDescr  =  $result->{$OID_hrStorageDescr.".".$partition };
$AllocationUnits  =  $result->{$OID_hrStorageAllocationUnits.".".$partition };
$Size  =  $result->{$OID_hrStorageSize.".".$partition };
$Used  =  $result->{$OID_hrStorageUsed.".".$partition };

$hrStorageLabel = $hrStorageDescr;
if ($hrStorageDescr =~ /Label:(.*) Serial Number/) {
    $hrStorageLabel = $1;
} else {
    $hrStorageLabel = '';
}


# Plugins var treatmen

if (!$Size){
    print "Disk CRITICAL - no output (-p number expected... it doesn't exist, try another disk number)\n";
    exit $ERRORS{'CRITICAL'};
}

if (($Size =~  /([0-9]+)/) && ($AllocationUnits =~ /([0-9]+)/)){

    if ($hrStorageDescr =~ /\:/){
        my @tab = split(/\:/, $hrStorageDescr);
        $hrStorageDescr = $tab[0] . ":";
    }

    if (!$Size){
        print "The number of the option -p is not a hard drive\n";
        exit $ERRORS{'CRITICAL'};
    }
    $tot = 1;
    $tot = $Size * $AllocationUnits;
    if (!$tot) {
        $tot = 1;
    }
    $used = $Used * $AllocationUnits;
    $pourcent = ($used * 100) / $tot;

    if (length($pourcent) > 2){
        @test = split (/\./, $pourcent);
        $pourcent = $test[0];
    }
    my $totMB = $tot / 1048576;
    my $usedMB = $used / 1048576;
    my $freeMB = $totMB - $usedMB;
    my $totGB = $totMB / 1024;
    my $usedGB = $usedMB / 1024;
    my $freeGB = $freeMB / 1024;
    
    # Plugin return code  
    if ($criticalMB ? ($freeMB <= $critical) : ($pourcent >= $critical)) {
        print "Disk CRITICAL - ";
        $return_code = 2;
    } elsif ($warningMB ? ($freeMB <= $warning) : ($pourcent >= $warning)) {
        print "Disk WARNING - ";
        $return_code = 1;
    } else {
        print "Disk OK - ";
        $return_code = 0;
    }

    if ($hrStorageDescr){
        $hrStorageDescr =~ s/\ //g if (defined($opt_t) && $opt_t eq "AS400");
        my $warn; my $crit;
        $warn = $warningMB ? $tot-$warning*1024*1024 : int($warning * $tot / 100);
        $crit = $criticalMB ? $tot-$critical*1024*1024 : int($critical * $tot / 100);
        if ($opt_M) {
            printf($hrStorageDescr . " TOTAL: %dMB USED: %dMB (%d%%) FREE: %dMB (%d%%)", $totMB, $usedMB, $pourcent, $freeMB, 100-$pourcent );
        } else {
           printf($hrStorageDescr . " TOTAL: %.3fGB USED: %.3fGB (%d%%) FREE: %.3fGB (%d%%)", $totGB, $usedGB, $pourcent, $freeGB, 100-$pourcent );
        }
        if ($opt_L) {
            print " - ".$hrStorageLabel;
        }
        print "|size=".$tot."B used=".$used."B;".$warn.";".$crit.";0;".$tot."\n";
        exit $return_code;
    } else {
        printf("TOTAL: %.3fGB USED: %.3fGB (%d%%)", $totMB, $usedMB, $pourcent );
        exit $return_code;
    }
} else {
    print "Disk CRITICAL - no output (-d number expected... it doesn't exist, try another disk number)\n";
    exit $ERRORS{'CRITICAL'};
}

sub print_usage () {
    print "\nUsage:\n";
    print "$PROGNAME\n";
    print "   -H (--hostname)   Hostname to query (required)\n";
    print "   -C (--community)  SNMP read community (defaults to public)\n";
    print "                     used with SNMP v1 and v2c\n";
    print "   -v (--snmp-version)  1 for SNMP v1 (default)\n";
    print "                        2 for SNMP v2c\n";
    print "                        3 for SNMP v3\n";
    print "   -P (--snmp-port)  SNMP port (default: 161)\n";
    print "   -k (--authkey)    snmp V3 key\n";
    print "   -u (--username)   snmp V3 username \n";
    print "   -p (--password)   snmp V3 password\n";
    print "   --authprotocol    protocol MD5/SHA  (v3)\n";
    print "   --privprotocol    encryption system (DES/AES)(v3) \n";
    print "   --privpassword    passphrase (v3) \n";
    print "   --64-bits         Use 64 bits OID\n";
    print "   --maxrepetitions  To use when you have the error: 'Message size exceeded buffer maxMsgSize'\n";
    print "                     Work only with SNMP v2c and v3 (Example: --maxrepetitions=1)\n";
    print "   --snmp-timeout    SNMP Timeout\n";
    print "   -d (--disk)       Set the disk (number expected) ex: 1, 2,... (default: 2 )\n";
    print "   -n (--name)       Allows to use disk name with option -d instead of disk oid index\n";
    print "                     (ex: -d \"C:\" -n, -d \"E:\" -n, -d \"Swap Memory\" -n, -d \"Real Memory\" -n\n";
    print "                     (choose an unique expression for each disk)\n";
    print "   -s (--show)       Lists all disks (debug mode)\n";
    print "   -w (--warn)       Minimum fill level at which a warning message will be generated\n";
    print "                     (default 80)\n";
    print "                     By using the optional suffixes MB/GB the argument is interpreted as absolute size \n";
    print "                     and it becomes a threshold for free space. (ex. 100MB; 3GB)\n";
    print "   -c (--crit)       Minimum fill level at which a critical message will be generated\n";
    print "                     (default 95)\n";
    print "                     By using the optional suffixes MB/GB the argument is interpreted as absolute size \n";
    print "                     and it becomes a threshold for free space. (ex. 50MB; 1GB)\n";
    print "                     ex.: -w 1GB -c 256MB generates a warning when free space reaches 1GB\n";
    print "                          and critical when there are less than 256MB left\n";
    print "   -V (--version)    Plugin version\n";
    print "   -L                add Windows drive label to output\n";
    print "   -M                Shows the size in output in MB instead of GB\n";
    print "   -t                To use for AIX or AS/400 (ex. 'AIX' or 'AS/400')\n";
    print "   -a (--cache)      Updates cache file every n hours instead of doing snmpwalk for every check (default: 3)\n";
    print "   -h (--help)       usage help\n";

}

sub print_help () {
    print "##############################################\n";
    print "#    Copyright (c) 2004-2013 Centreon        #\n";
    print "#    Bugs to http://forge.centreon.com/      #\n";
    print "##############################################\n";
    print_usage();
    print "\n";
}
