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

# FIXME: Crapy copy n paste! Consolidate with other mysql_* parse functions
def parse_mysql_slave(info):
    def parse_line(l):
        if ':' in l[0]:
            val = ' '.join(l[1:])

            # Parse some values
            try:
                val = int(val)
            except ValueError:
                if val == 'Yes':
                    val = True
                elif val == 'No':
                    val = False
                elif val == 'None':
                    val = None
            return line[0][:-1], val
        else:
            return None, None

    parsed = {}
    instance = False
    data = {}
    for line in info:
        if line[0].startswith("[["):
            instance = line[0][2:-2]
            if instance == "":
                instance = "mysql"
            parsed[instance] = {}
        elif instance:
            key, value = parse_line(line)
            if key:
                parsed[instance][key] = value

    # Support for old Plugin version
    if not instance:
        parsed['mysql'] = {}
        for line in info:
            key, value = parse_line(line)
            if key:
                parsed['mysql'][key] = value

    return parsed


def inventory_mysql_slave(parsed):
    for instance, values in parsed.items():
        if len(values) > 0:
            yield instance, {}


def check_mysql_slave(item, params, parsed):
    if parsed.get(item):
        data = parsed[item]

        state = 0
        perfdata = []
        output = []

        if data['Slave_IO_Running']:
            output.append('Slave-IO: running')
        else:
            output.append('Slave-IO: not running(!!)')
            state = 2

        if data['Slave_SQL_Running']:
            output.append('Slave-SQL: running')

            # Makes only sense to monitor the age when the SQL slave is running
            if data['Seconds_Behind_Master'] == 'NULL':
                output.append('Time behind master: NULL (Lost connection?)(!!)')
                state = 2
            else:
                out = 'Time behind Master: %s' % get_age_human_readable(data['Seconds_Behind_Master'])
                warn, crit = params.get('seconds_behind_master', (None, None))
                if crit != None and data['Seconds_Behind_Master'] > crit:
                    state = 2
                    out += '(!!)'
                elif warn != None and data['Seconds_Behind_Master'] > warn:
                    state = max(state, 1)
                    out += '(!)'
                output.append(out)
                perfdata.append(('sync_latency', data['Seconds_Behind_Master'], warn, crit))
        else:
            output.append('Slave-SQL: not running(!!)')
            state = 2

        return state, ', '.join(output), perfdata

check_info['mysql_slave'] = {
    "parse_function"          : parse_mysql_slave,
    "inventory_function"      : inventory_mysql_slave,
    "check_function"          : check_mysql_slave,
    "service_description"     : "MySQL DB Slave %s",
    "has_perfdata"            : True,
    "group"                   : "mysql_slave",
}

