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

# <<<netapp_api_vf_snapvault:sep(9)>>>
# snapvault /vol/ipb_datap/   status idle state snapvaulted   lag-time 53812  source-system 172.31.12.15
# snapvault /vol/ipb_datas/   status idle state snapvaulted   lag-time 53812  source-system 172.31.12.15
# snapvault /vol/ipb_user/    status idle state snapvaulted   lag-time 97007  source-system 172.31.12.15
# snapvault /vol/ipb_vol0/    status idle state snapvaulted   lag-time 97011  source-system 172.31.12.15

discovery_snapvault = []


def _cleanse_item_name(name):
    return name.replace("$", "_")


def parse_netapp_api_snapvault(info):
    parsed = {}
    for line in info:
        parsed_line = dict([tuple(i.split(' ', 1)) for i in line])
        # Whether the item will be named after the snapvault or destination-location
        # values depends on the user's configuration (discovery parameters). For simplicity,
        # the same line is referenced to both in the parsed dictionary, so that the items
        # can easily be retrieved using the .get method, without needing to worry
        # about what the discovery parameters are.
        parsed[_cleanse_item_name(parsed_line['snapvault'])] = parsed_line
        if 'destination-location' in parsed_line:
            # 7mode netapp data comes without destination-location. We currently do not have
            # a test case for this.
            parsed[_cleanse_item_name(parsed_line['destination-location'])] = parsed_line
    return parsed


def _discovery_snapvault():
    params = host_extra_conf_merged(host_name(), discovery_snapvault)
    if not params:
        return {'exclude_destination_vserver': False}
    return params


def _prefilter_items(parsed, exclude_vserver):
    if exclude_vserver:
        return [i for i in parsed.items() if ':' not in i[0]]
    return [i for i in parsed.items() if ':' in i[0] or 'destination-location' not in i[1]]


def discover_netapp_api_snapvault(parsed):
    params = _discovery_snapvault()
    for snapvault, values in _prefilter_items(parsed, params['exclude_destination_vserver']):
        if "lag-time" in values:
            yield snapvault, {}


def check_netapp_api_snapvault(item, params, parsed):

    snapvault = parsed.get(item)

    if not snapvault:
        return

    for key in ["source-system", "destination-system", "policy", "status", "state"]:
        if key in snapvault:
            yield 0, "%s: %s" % (key.title(), snapvault[key])

    lag_time = snapvault.get("lag-time")
    if not lag_time:
        return

    lag_time = int(lag_time)
    state = 0
    if params:
        levels = None
        snapvault_policy = snapvault.get("policy")

        for name, policy_levels in params.get("policy_lag_time", []):
            if name == snapvault_policy:
                levels = policy_levels
                break

        if not levels and params.get("lag_time"):
            levels = params["lag_time"]

        if levels:
            warn, crit = levels
            if lag_time >= crit:
                state = 2
            elif lag_time >= warn:
                state = 1

    yield state, "Lag-Time: %s" % get_age_human_readable(lag_time)


check_info["netapp_api_snapvault"] = {
    'parse_function': parse_netapp_api_snapvault,
    'check_function': check_netapp_api_snapvault,
    'inventory_function': discover_netapp_api_snapvault,
    'group': "snapvault",
    'service_description': 'Snapvault %s',
}
