#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# <<<mssql_instance:sep(124)>>>
# MSSQL_MSSQLSERVER|config|10.50.1600.1|Enterprise Edition|BLABLA
# <<<mssql_instance:sep(124)>>>
# MSSQL_SQLEXPRESS|config|10.50.1600.1|Express Edition|
# <<<mssql_instance:sep(124)>>>
# MSSQL_MICROSOFT##SSEE|config|9.00.5000.00|Windows Internal Database|
# <<<mssql_instance:sep(124)>>>
# MSSQL_MSSQLSERVER|state|0|[DBNETLIB][ConnectionOpen (Connect()).]SQL Server existiert nicht oder Zugriff verweigert.
# <<<mssql_instance:sep(124)>>>
# MSSQL_SQLEXPRESS|state|1|[DBNETLIB][ConnectionOpen (Connect()).]SQL Server existiert nicht oder Zugriff verweigert.
# <<<mssql_instance:sep(124)>>>
# MSSQL_MICROSOFT##SSEE|state|0|[DBNETLIB][ConnectionOpen (Connect()).]SQL Server existiert nicht oder Zugriff verweigert.

# <<<mssql_instance:sep(124)>>>
# ERROR: Failed to gather SQL server instances

def parse_mssql_instance(info):
    parsed = {}

    for line in info:
        if line[0].startswith("ERROR:"):
            continue
        elif line[0][:6] == "MSSQL_":
            # Remove the MSSQL_ prefix from the ID for this check
            instance_id = line[0][6:]
        else:
            instance_id = line[0]

        instance = parsed.setdefault(instance_id, {
            # it may happen that the state line is missing, add some fallback as default here
            "state"     : "0",
            "error_msg" : "Unable to connect to database (Agent reported no state)",
        })

        if line[1] == "config":
            instance.update({
                "version"      : line[2],
                "edition"      : line[3],
                "cluster_name" : line[4],
            })
        elif line[1] == "state":
            instance.update({
                "state"        : line[2],
                "error_msg"    : "|".join(line[3:]),
            })

    return parsed


def inventory_mssql_instance(parsed):
    for instance_id, instance in parsed.items():
        yield instance_id, {}


def check_mssql_instance(item, params, parsed):
    instance = parsed.get(item)
    if not instance:
        return

    state = 2
    if params is not None and \
       params.get("map_connection_state") is not None:
        state = params["map_connection_state"]

    if instance["state"] == "0":
        yield state, "Failed to connect to database (%s)" % instance["error_msg"]

    yield 0, "Server is running version %s, %s" % (instance["version"], instance["edition"])

    if instance["cluster_name"] != "":
        yield 0, "clustered as %s" % instance["cluster_name"]


check_info["mssql_instance"] = {
    'parse_function'      : parse_mssql_instance,
    'check_function'      : check_mssql_instance,
    'inventory_function'  : inventory_mssql_instance,
    'service_description' : 'MSSQL %s Instance',
    'group'               : 'mssql_instance',
}
