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

# <<<oracle_sql:sep(58)>>>
# [[[SID-1|SQL-A]]]
# details:DETAILS
# perfdata:NAME=VAL;WARN;CRIT;MIN;MAX NAME=VAL;WARN;CRIT;MIN;MAX ...
# perfdata:NAME=VAL;WARN;CRIT;MIN;MAX ...
# long:LONG
# long:LONG
# ...
# exit:CODE
# elapsed:TS
# [[[SID-2|SQL-B]]]
# details:DETAILS
# perfdata:
# long:LONG
# long:LONG
# ...
# exit:CODE
# elapsed:TS


def parse_oracle_sql(info):
    def parse_perfdata(line):
        perfdata = []
        for entry in line.split():
            if not entry:
                continue
            var_name, data_str = entry.split("=", 1)
            perf_entry = [var_name]
            for data_entry in data_str.split(";"):
                if "." in data_entry:
                    conversion = float
                else:
                    conversion = int
                try:
                    perf_entry.append(conversion(data_entry))
                except:
                    perf_entry.append(None)
            perfdata.append(tuple(perf_entry))
        return perfdata

    parsed = {}
    instance = None
    for line in info:
        if line[0].startswith("[[[") and line[0].endswith("]]]"):
            item_name = tuple(line[0][3:-3].split("|"))
            instance = parsed.setdefault(
                ("%s SQL %s" % item_name).upper(), {
                    "details": [],
                    "perfdata": [],
                    "long": [],
                    "exit": 0,
                    "elapsed": None,
                    "parsing_error": {},
                })
            continue

        if instance is None:
            continue

        key = line[0]
        infotext = ":".join(line[1:]).strip()
        if key.endswith("ERROR") or key.startswith('ERROR at line') or "|FAILURE|" in key:
            instance["parsing_error"].setdefault(("instance", "PL/SQL failure", 2), [])\
                                     .append("%s: %s" % (key.split("|")[-1], infotext))

        elif key in ["details", "long"]:
            instance[key].append(infotext)

        elif key == "perfdata":
            try:
                instance[key] += parse_perfdata(line[1])
            except:
                instance["parsing_error"].setdefault(("perfdata", "Perfdata error", 3), [])\
                                         .append(infotext)

        elif key == "exit":
            instance[key] = int(line[1])

        elif key == "elapsed":
            instance[key] = float(line[1])

        else:
            instance["parsing_error"].setdefault(("unknown", "Unknown error", 3), [])\
                                     .append(":".join(line).strip())

    return parsed


def inventory_oracle_sql(parsed):
    for instance in parsed:
        yield instance, {}


def check_oracle_sql(item, params, parsed):
    if item not in parsed:
        return

    data = parsed[item]
    for (error_key, error_title, error_state), error_lines in data["parsing_error"].iteritems():
        error_state = params.get("%s_error_state" % error_key, error_state)
        yield error_state, "%s: %s" % (error_title, " ".join(error_lines))

    perfdata = data["perfdata"]
    elapsed_time = data["elapsed"]
    if elapsed_time is not None:
        perfdata.append(("elapsed_time", elapsed_time))

    yield data["exit"], ", ".join(data["details"]), perfdata

    if data["long"]:
        yield 0, "\n%s" % "\n".join(data["long"])


check_info['oracle_sql'] = {
    'parse_function': parse_oracle_sql,
    'inventory_function': inventory_oracle_sql,
    'check_function': check_oracle_sql,
    'service_description': 'ORA %s',
    'has_perfdata': True,
    'group': 'oracle_sql',
}
