#!/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_prod_version(entry):
    if entry.startswith("8."):
        version = "2000"
    elif entry.startswith("9."):
        version = "2005"
    elif entry.startswith("10.0"):
        version = "2008"
    elif entry.startswith("10.50"):
        version = "2008R2"
    elif entry.startswith("11."):
        version = "2012"
    elif entry.startswith("12."):
        version = "2014"
    elif entry.startswith("13."):
        version = "2016"
    elif entry.startswith("14."):
        version = "2017"
    else:
        return "unknown[%s]" % entry
    return "Microsoft SQL Server %s" % version


def parse_mssql_instance(info):
    parsed = {}
    for line in info:
        if line[0].startswith("ERROR:") or len(line) < 2 or line[1] not in [
                "config", "state", "details"
        ]:
            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_info": "%s - %s" % (line[2], line[3]),
                "cluster_name": line[4],
            })
        elif line[1] == "state":
            instance.update({
                "state": line[2],
                "error_msg": "|".join(line[3:]),
            })

        elif line[1] == "details":
            _parse_prod_version(line[2])
            instance.update({
                "prod_version_info": "%s (%s) (%s) - %s" %
                                     (_parse_prod_version(line[2]), line[3], line[2], line[4])
            })

    return parsed


def inventory_mssql_instance(parsed):
    for instance_id in parsed.iterkeys():
        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, "Version: %s" % instance.get("prod_version_info", instance["version_info"])
    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',
}
