#!/usr/bin/env python
# COPYRIGHT
# 
# This software is Copyright (c)  2011 NETWAYS GmbH, Gunnar Beutner
#                                 <support@netways.de>
# 
# (Except where explicitly superseded by other copyright notices)
# 
# LICENSE
# 
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from http://www.fsf.org.
# 
# This work 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.fsf.org.
# 
# 
# CONTRIBUTION SUBMISSION POLICY:
# 
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to NETWAYS GmbH.)
# 
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# this Software, to NETWAYS GmbH, you confirm that
# you are the copyright holder for those contributions and you grant
# NETWAYS GmbH a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
# 
# Nagios and the Nagios logo are registered trademarks of Ethan Galstad.

import sys
import re
import urllib2
from nagaconda import Plugin

try:
    import simplejson as json
except ImportError:
    try:
        import json
    except ImportError:
        print "This plugin requires Python 2.6 or the simplejson module."
        sys.exit(4)

helptext = """
Example:

./check_gude_2151 -h <host> -u admin -p <password> \\
    -w check_gude_2151::sensor2_1::value=~:25 \\
    -c check_gude_2151::sensor2_1::value=~:30 \\
    -c check_gude_2151::output_Output1::state=1:

This check would be CRITICAL if one of the following conditions are met:
-The HTTP check request fails (wrong password, device unavailable, etc.).
-The second sensor's value is above 30.
-The first output state is 'off'.

The check would return a WARNING if the sensor value is above 25 unless
one of the CRITICAL conditions were encountered - in which case
the CRITICAL condition takes precedence.
"""

plugin = Plugin("Checks the status of Gude Expert Net Control 2151 devices.",
                "1.0", helptext)

plugin.add_option('h', 'host', 'The hostname of the device.', required=True)
plugin.add_option('u', 'user', 'Username')
plugin.add_option('p', 'password', 'Password')

plugin.enable_status('warning')
plugin.enable_status('critical')

plugin.start()

base_url = "http://%s/" % (plugin.options.host)

if plugin.options.user != None and plugin.options.password != None:
    pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    pwmgr.add_password(None, base_url, plugin.options.user,
            plugin.options.password)

    handler = urllib2.HTTPBasicAuthHandler(pwmgr)

    opener = urllib2.build_opener(handler)
else:
    opener = urllib2.build_opener()

try:
#    response = open('test/output.json', 'r')
    response = opener.open(base_url + "statusjsn.js?components=1379")
except urllib2.URLError, e:
    plugin.set_critical()
    plugin.set_status_message("Could not check device status: " + str(e))
    plugin.finish()

status_json = response.read()

status = json.loads(status_json)

plugin.set_value('check_gude_2151::outputs::count', len(status['outputs']))

for output in status['outputs']:
    clean_name = re.sub('[^A-Za-z0-9]', '', output['name'])
    plugin.set_value('output_%s::check_gude_2151::state' % (clean_name),
        output['state'])

plugin.set_value('check_gude_2151::sensors::count', len(status['sensor']))

for sensor in status['sensor']:
    name = 'sensor%s_%s::check_gude_2151' % (sensor['port'], sensor['sub'])
    plugin.set_value('%s::status' % (name), sensor['status'])

    if sensor['type'] == 2:
        unit = '%'
    else:
        unit = None

    kwargs = {
        'lowest': sensor['min'],
        'highest': sensor['max']
    }

    if unit != None:
        kwargs['scale'] = unit

    plugin.set_value('%s::value' % (name), sensor['value'], **kwargs)

plugin.finish()
