#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2017             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.

# example output
# <<<mssql_databases>>>^M
# MSSQL_MSSQL46 CorreLog_Report_T ONLINE FULL 0 0^M
# MSSQL_MSSQL46 DASH_CONFIG_T ONLINE FULL 0 0^M
# MSSQL_MSSQL46 master ONLINE SIMPLE 0 0^M
# MSSQL_MSSQL46 model ONLINE FULL 0 0^M
# MSSQL_MSSQL46 msdb ONLINE SIMPLE 0 0^M
# MSSQL_MSSQL46 NOC_ALARM_T ONLINE FULL 0 1^M
# MSSQL_MSSQL46 NOC_CONFIG_T ONLINE FULL 0 0^M
# MSSQL_MSSQL46 tempdb ONLINE SIMPLE 0 0^M
# MSSQL_MSSQL46 test_autoclose ONLINE FULL 1 0^M
# MSSQL_MSSQL46 test_autoclose RECOVERY PENDING FULL 1 0^M


def parse_mssql_databases(info):
    parsed = {}
    headers = ['Instance', 'DBname', 'Status', 'Recovery', 'auto_close', 'auto_shrink']

    for line in info:
        if line == headers:
            continue

        if len(line) == 6:
            data = dict(zip(headers, line))
        elif len(line) == 7:
            data = dict(zip(headers, line[:2] + ["%s %s" % (line[2], line[3])] + line[-3:]))
        else:
            continue
        parsed.setdefault("%s %s" % (data["Instance"], data["DBname"]), data)

    return parsed


def check_mssql_databases(item, params, parsed):
    data = parsed.get(item)
    if data is None:
        raise MKCounterWrapped("Login into database failed")

    map_states = {
        "1": (1, "on"),
        "0": (0, "off"),
    }

    db_state = data["Status"]
    if db_state.startswith("ERROR: "):
        yield 2, db_state[7:]
        return
    state = params.get("map_db_states", {}).get(db_state.replace(" ", "_").upper(), 0)
    yield state, 'Status: %s' % db_state
    yield 0, 'Recovery: %s' % data["Recovery"]

    for what in ["close", "shrink"]:
        state, state_readable = map_states[data["auto_%s" % what]]
        state = params.get("map_auto_%s_state" % what, {}).get(state_readable, state)
        yield state, 'Auto %s: %s' % (what, state_readable)


check_info['mssql_databases'] = {
    'parse_function': parse_mssql_databases,
    'inventory_function': discover(),
    'check_function': check_mssql_databases,
    'service_description': 'MSSQL %s Database',
    'group': 'mssql_databases',
}
