#!/usr/local/bin/perl -w
# $Id: check_mem.pl 2 2002-02-28 06:42:51Z egalstad $

# Original script stolen from:
# check_mem.pl Copyright (C) 2000 Dan Larsson <dl@tyfon.net>
# hacked by
# Justin Ellison <justin@techadvise.com>
#
# Modified by BParish for use with SNMP 4/15/2010
#
# 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, or (at your option) any later version.
#
# 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 (or with Nagios);  if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA

use strict;
use Getopt::Std;

my $VERSION = '2.2';   		# ARBITRARY VERSION SET TO CONTROL MY CHANGES TO THIS SCRIPT
my $UPDATE = '05.07.2010';

# Predefined exit codes for Nagios
use vars qw($opt_c $opt_f $opt_u $opt_w $opt_C $opt_v %exit_codes);
%exit_codes   = ('UNKNOWN' ,-1,
        	 'OK'      , 0,
                 'WARNING' , 1,
                 'CRITICAL', 2,
                 );

$opt_C = 1;
# $opt_v = 1;

# Get the numbers:
my ($total_memory_kb,$free_memory_kb,$used_memory_kb,$caches_kb) = get_memory_info();

# ALWAYS ASSUME THE "-C" OPTION (FACTOR IN CACHES):
$used_memory_kb -= $caches_kb;
$free_memory_kb += $caches_kb;

# Round to the nearest KB
$free_memory_kb = sprintf('%d',$free_memory_kb);
$used_memory_kb = sprintf('%d',$used_memory_kb);
$caches_kb = sprintf('%d',$caches_kb);

my ($used,$free,$caches) = @_;
    

	#  THIS ONE REPORTS BACK SINGLE LINE (COMPAT. w/ EXEC):
print "UCD-SNMP-MIB::memTotalReal.0 = INTEGER: $total_memory_kb kB||UCD-SNMP-MIB::memAvailReal.0 = INTEGER: $free_memory_kb kB";
	#  THIS LINE REPORTS MULTI-LINE OUTPUT (COMPAT. w. EXTEND):
print "\nUCD-SNMP-MIB::memTotalReal.0 = INTEGER: $total_memory_kb kB\nUCD-SNMP-MIB::memAvailReal.0 = INTEGER: $free_memory_kb kB\n";

sub get_memory_info {
    my $used_memory_kb  = 0;
    my $free_memory_kb  = 0;
    my $total_memory_kb = 0;
    my $caches_kb       = 0;

    my $uname;
    if ( -e '/usr/bin/uname') {
        $uname = `/usr/bin/uname -a`;
    }
    elsif ( -e '/bin/uname') {
        $uname = `/bin/uname -a`;
    }
    else {
        die "Unable to find uname in /usr/bin or /bin!\n";
    }
    print "uname returns $uname" if ($opt_v);
    if ( $uname =~ /Linux/ ) {
        my @meminfo = `/bin/cat /proc/meminfo`;
        foreach (@meminfo) {
            chomp;
            if (/^Mem(Total|Free):\s+(\d+) kB/) {
                my $counter_name = $1;
                if ($counter_name eq 'Free') {
                    $free_memory_kb = $2;
                }
                elsif ($counter_name eq 'Total') {
                    $total_memory_kb = $2;
                }
            }
            elsif (/^(Buffers|Cached):\s+(\d+) kB/) {
                $caches_kb += $2;
            }
        }
        $used_memory_kb = $total_memory_kb - $free_memory_kb;
    }
    elsif ( $uname =~ /SunOS/ ) {
	print "Found Sun\n" if ($opt_v);
	print join(',',@INC) . "\n" if ($opt_v);
        eval "use Sun::Solaris::Kstat";
        if ($@) { #Kstat not available
print $@ . "\n";
            if ($opt_C) {
                print "You can't report on Solaris caches without Sun::Solaris::Kstat available!\n";
                exit $exit_codes{UNKNOWN};
            }
            my @vmstat = `/usr/bin/vmstat 1 2`;
            my $line;
            foreach (@vmstat) {
              chomp;
              $line = $_;
            }
            $free_memory_kb = (split(/ /,$line))[5] / 1024;
            my @prtconf = `/usr/sbin/prtconf`;
            foreach (@prtconf) {
                if (/^Memory size: (\d+) Megabytes/) {
                    $total_memory_kb = $1 * 1024;
                }
            }
            $used_memory_kb = $total_memory_kb - $free_memory_kb;
            
        }
        else { # We have kstat
	    print "Found Kstat\n" if ($opt_v);
            my $kstat = Sun::Solaris::Kstat->new();
            my $phys_pages = ${kstat}->{unix}->{0}->{system_pages}->{physmem};
            my $free_pages = ${kstat}->{unix}->{0}->{system_pages}->{freemem};
	    # print "Physical Pages: $phys_pages, Free Pages: $free_pages\n";
            my $arc_size = (exists ${kstat}->{zfs} && ${kstat}->{zfs}->{0}->{arcstats}->{size}) ?
                 ${kstat}->{zfs}->{0}->{arcstats}->{size} / 1024 
                 : 0;
            $caches_kb += $arc_size;
            my $pagesize = `pagesize`;
 	    $pagesize = 8192 if (! $pagesize);
    
            $total_memory_kb = $phys_pages * $pagesize / 1024;
            $free_memory_kb = $free_pages * $pagesize / 1024;
            $used_memory_kb = $total_memory_kb - $free_memory_kb;
        }
    }
    else {
        if ($opt_C) {
            print "You can't report on $uname caches!\n";
            exit $exit_codes{UNKNOWN};
        }
    	my $command_line = `vmstat | tail -1 | awk '{print \$4,\$5}'`;
    	chomp $command_line;
        my @memlist      = split(/ /, $command_line);
    
        # Define the calculating scalars
        $used_memory_kb  = $memlist[0]/1024;
        $free_memory_kb = $memlist[1]/1024;
        $total_memory_kb = $used_memory_kb + $free_memory_kb;
    }
    return ($total_memory_kb,$free_memory_kb,$used_memory_kb,$caches_kb);
}