#!/usr/bin/env python

# Copyright 2004 Jacob Joseph<jacob@jjoseph.org>
# 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; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

import string, sys

############################################################################
# Some generic functions( would normally be imported, but I want only
# one file)
############################################################################
def error( msg, err=10):
    sys.stderr.write( msg)
    sys.exit( err)

def tryint( s):
    try:
        i = int( s)
    except( ValueError):
        error( "Error: Failed to convert '%s' to int" % s, 11)
    return i

def tryintarr( arr):
    try:
        iarr = map( int, arr)
    except ValueError:
        error( "Error: failed to convert '%s' to ints", 13)
    return iarr

def tryfloat( s):
    try:
        f = float( s)
    except( ValueError):
        error( "Error: Failed to convert '%s' to float" % s, 12)

def tryfloatarr( arr):
    try:
        farr = map( float, arr)
    except ValueError:
        error( "Error: failed to convert '%s' to floats", 13)
    return farr

def outofrange( val, limitarr):
    if len( limitarr) != 2:
        error( "outofrange() requires limit of len = 2", 14)
    if val <= limitarr[0] or val >= limitarr[1]:
        return 1
    return 0

def comparearr( arr1, limit):
    "true if any element i in arr1 exceeds limit"
    
    if len( arr1) != len( limit):
        error( "compare() requires arrays of equal length.", 15)
    for i in range( len(arr1)):
        if arr1[i] >= limit[i]:
            return 1
    return 0
############################################################################

### Parse the command line
def parseargs( argv, usagefn):
    """Expecting something like:
    -w <float,float,float> -c <float,float,float>"""
    
    warnval = None
    critval = None

    i = 1;
    while i < len(argv):
        arg = argv[i]
        if arg == "--help" or arg == "-h":
            usage( argv[0])
            sys.exit(4)
        elif arg == "-w":
            # Convert next arg into list of floats
            i = i + 1
            warnval = tryfloatarr( string.split( argv[i], ','))
        elif arg == "-c":
            # Convert next arg into list of floats
            i = i + 1
            critval = tryfloatarr( string.split( argv[i], ','))
        i = i + 1

    # A basic sanity check
    if not warnval or not critval or \
        len(warnval) != 3 or len(critval) != 3:
            sys.stderr.write( "Failed to parse args.\n")
            usagefn( argv[0])
            sys.exit(5);

    return warnval, critval


### Usage information
def usage( progname):
    msg = """%s
The nagios plugins come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
Copyright (c) 2002 Paul Komarek
Copyright (c) 2003,2004 Jacob Joseph <jmjoseph@andrew.cmu.edu>

This plugin looks in /proc/loadavg to determine load.

Usage: %s -w <load> -c <load>
       %s --help|-h

Where <load> is a list of 3 floats corresponding to the 1min,5min, and
15min load averages.  ex: '-w 1.2,1.5,2 -c 2.5,3,3.2'
"""

    print msg % (progname, progname, progname)
    return


def getload():
    "Get load info from /proc/loadavg"
    
    path = "/proc/loadavg"
    load = string.split( open( path).readline())

    load = tryfloatarr( load[:3])

    return load


####################################
# "main"
####################################
if __name__ == "__main__":

    # Get args.
    warnval, critval = parseargs( sys.argv, usage)

    # Get current load
    load = getload()
    
    # Check the result against warnval and critval
    msg = ""
    if comparearr( load, critval):
        msg = msg + "CRITICAL - "
        ret = 2        
    elif comparearr( load, warnval):
        msg = msg + "WARNING - "
        ret = 1
    else:
        msg = msg + "OK - "
        ret = 0

    msg = msg + "load average: %.2f, %.2f, %.2f" % \
           (load[0], load[1], load[2])

    print msg
    sys.exit(ret)
    
