#!/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.

# Old agent
# <<<mssql_backup>>>
# MSSQL_SQLEXPRESS test123 1331207325

# Newer agent
# <<<mssql_backup>>>
# MSSQL_SQL0x master 2016-07-08 20:20:27
# MSSQL_SQL0x model 2016-07-08 20:20:28
# MSSQL_SQL0x model 2016-07-12 09:09:42
# MSSQL_SQL0x model 2016-07-11 20:20:07
# MSSQL_SQL0x msdb 2016-07-08 20:20:43
# MSSQL_SQL0x msdb 2016-07-11 20:20:07

# New agent (added backup type)
# <<<mssql_backup>>>
# MSSQL_SQL0x master 2016-07-08 20:20:27 D
# MSSQL_SQL0x model 2016-07-08 20:20:28 D
# MSSQL_SQL0x model 2016-07-12 09:09:42 L
# MSSQL_SQL0x model 2016-07-11 20:20:07 I
# MSSQL_SQL0x msdb 2016-07-08 20:20:43 D
# MSSQL_SQL0x msdb 2016-07-11 20:20:07 I


factory_settings["mssql_backup_default_levels"] = {
    "database":             (None, None),
    "database_diff":        (None, None),
    "log":                  (None, None),
    "file_or_filegroup":    (None, None),
    "file_diff":            (None, None),
    "partial":              (None, None),
    "partial_diff":         (None, None),
    "unspecific":           (None, None),
}


def parse_mssql_backup(info):

    def get_backup_type_name(backup_type):
        return {
            "D": "database ",
            "I": "database diff ",
            "L": "log ",
            "F": "file or filegroup ",
            "G": "file diff ",
            "P": "partial ",
            "Q": "partial diff ",
            "-": "unspecific ",
        }.get(backup_type, "")

    parsed = []
    for line in info:
        if len(line) not in [3, 4, 5]:
            continue

        # read data
        backup_date = None
        if len(line) == 5:
            inst, tablespace, backup_date, backup_time, backup_type = line
        elif len(line) == 4:
            inst, tablespace, backup_date, backup_time = line
            backup_type = None
        elif len(line) == 3:
            inst, tablespace, backup_timestamp = line
            backup_type = None

        # construct content
        db_system = inst + ' ' + tablespace

        if backup_date:
            # TODO: Timezone issue? Agent should always send UTC timestamp.
            timestamp = time.mktime(time.strptime(
                backup_date + ' ' + backup_time, '%Y-%m-%d %H:%M:%S')
            )
        else:
            timestamp = int(backup_timestamp)

        backup_type_name = get_backup_type_name(backup_type)

        if backup_type == None:
            perfkey = "seconds"
        else:
            perfkey = "backup_age_%s" % backup_type_name.strip().replace(" ", "_")

        parsed.append((db_system, timestamp, backup_type_name, perfkey))

    return parsed


def inventory_mssql_backup(parsed):
    return [ (line[0], {})
             for line in parsed
             if len(line) in [3, 4, 5] ]


def check_mssql_backup(item, params, parsed):
    found_instance = False
    for db_system, timestamp, backup_type_name, perfkey in parsed:
        if item != db_system:
            continue
        found_instance = True

        if not isinstance(params, dict):
            params = {"database": params}

        if backup_type_name == "":  # use "database" parameters as default for old agent output
            age_warn, age_crit = params["database"]
        else:
            backup_type_var = backup_type_name.strip().replace(" ", "_")
            age_warn, age_crit = params.get(backup_type_var, (None, None))

        state = 0
        sec_ago = time.time() - timestamp
        if age_crit is not None and sec_ago >= age_crit:
            state = 2
        elif age_warn is not None and sec_ago >= age_warn:
            state = 1

        perfdata = [(perfkey, sec_ago, age_warn, age_crit)]
        infotext = 'Last %sbackup was at %s (%s ago)' % (
            backup_type_name,
            time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)),
            get_age_human_readable(sec_ago)
        )

        if state != 0:
            infotext += " (warn/crit at %s/%s)" % (
                get_age_human_readable(age_warn), get_age_human_readable(age_crit)
            )

        yield state, infotext, perfdata

    if not found_instance:
        # Assume general connection problem to the database, which is reported
        # by the "X Instance" service and skip this check.
        raise MKCounterWrapped("Failed to connect to database")


check_info['mssql_backup'] = {
    'parse_function':      parse_mssql_backup,
    'check_function':      check_mssql_backup,
    'inventory_function':  inventory_mssql_backup,
    'service_description': 'MSSQL %s Backup',
    'has_perfdata':        True,
    'group':               'mssql_backup',
    'default_levels_variable': 'mssql_backup_default_levels',
}
