#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Biodec 2014                            info@biodec.com |
# +------------------------------------------------------------------+
#

# Example of plugin output
#<<facter>>
#{architecture:amd64,facterversion:1.6.10,hardwareisa:unknown,hardwaremodel:x86_64}

import json
import couchdb
import ConfigParser
import os

# the inventory function, checks the agent output and create a list of items
def inventory_facter(info):
    # begin with empty inventory
    inventory = []
    info = info[0][0]
    name="facter_%s" % ipaddresses.get(g_hostname)
    inventory.append((name, None))
    return inventory

# the couchdb-speaking function
def send_data(info):
    #conn_string:http://${user}:${password}@${host}:${port}/
    #server = couchdb.Server("http://admin:admin@localhost:5984/"
    # conn_strinf sta in /opt/omd/.../etc/
    configuration_file = os.path.join(os.environ['HOME'], 'etc/couchdb/couchdb.conf')
    if not os.path.isfile(configuration_file):
        return "Facter is active; CouchDB configuration file is absent."
    try:
        config = ConfigParser.ConfigParser()
        config.read(configuration_file)
        user = config.get('server', 'user')
        password = config.get('server', 'password')
        host = config.get('server', 'host')
        port = int(config.get('server', 'port'))
        db_name = config.get('server', 'dbname')
        conn_string = "http://%s:%s@%s:%d" % (user, password, host, port)
    except:
        return "Facter is active; CouchDB configuration file is misconfigured"
        
    server = couchdb.Server(conn_string)
    #host = str(ipaddress)
    #host = g_hostname
    host = ipaddresses.get(g_hostname)
    try:
        db = server[db_name]
    except couchdb.ResourceNotFound:
        db = server.create(db_name)
    except:
        return "Facter is active; CouchDB connection problems"
    info = json.loads(info)
    try:
        doc = db[host]
    except:
        db[host] = {host:info}
        db.commit()
        return
    doc["facter"] = info
    db.save(doc)
    db.commit()
    return

# the check function, process the output
def check_facter(item, params, info):
    ## manage differences between fqdn from facter
    ## and fqdn from check_mk
    # variables for the hostname <- from checkmk:
    # - hostname
    # - g_hostname
    # variables for the fqdn <- from checkmk ipaddress:
    # - ipaddress
    # - ipaddresses.get(hostname) or ipaddresses.get(g_hostname)
    # varible for the hostname <- from facter 
    # - not available
    # variables for the fqdn <- from facter
    # - info[0][0]["fqdn"]
    if info[0][0] == 'facter_not_installed':
        return (2, "CRIT - %s" % info[0][0])
    else:
        problems = send_data(info[0][0])
        if not problems:
            return (0, "OK - Facter is active")
        else:
            return (2, "CRIT - %s " % problems)

# declare the check to Check_MK
check_info['facter'] = {
    "check_function"          : check_facter,
    "inventory_function"      : inventory_facter,
    "service_description"     : "Facter facts",
    "has_perfdata"            : True,
}
