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

# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.2.4  "Failover LAN Interface"
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.2.6  "Primary unit (this device)"
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.2.7  "Secondary unit"
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.3.4  2
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.3.6  9     < These two values flip during
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.3.7  10    < failover
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.4.4  "LAN_FO GigabitEthernet0/0.777"
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.4.6  "Active unit"
# .1.3.6.1.4.1.9.9.147.1.2.1.1.1.4.7  "Standby unit"

# [['Failover LAN Interface', '2', 'LAN_FO GigabitEthernet0/0.777'],
#  ['Primary unit', '9', 'Active unit'],
#  ['Secondary unit (this device)', '10', 'Standby unit']]

factory_settings["cisco_asa_failover_default_levels"] = {
            "primary"            : "active",
            "secondary"          : "standby",
            "failover_state"     : 1,
}


def parse_cisco_asa_failover(info):
    def parse_line(line):
        role = line[0].split(" ")[0].lower()
        data = [role, line[1], line[2].lower()]
        return data

    parsed = {}
    for line in info:
        if "this device" in line[0].lower():
            parsed["local"] = parse_line(line)
        elif "failover" in line[0].lower():
            parsed["failover"] = line
        else:
            parsed["remote"] = parse_line(line)
    return parsed


def inventory_cisco_asa_failover(parsed):
    if not "failover off" in parsed["local"][2]:
        yield (None, {})


cisco_asa_state_names = {
    "1": "other",
    "2": "up",
    "3": "down",
    "4": "error",
    "5": "overTemp",
    "6": "busy",
    "7": "noMedia",
    "8": "backup",
    "9": "active",
    "10": "standby",
}


def _convert_params(params):
    if isinstance(params, int):
        # Very old case: primary state was remembered during discovery
        # and stored as an integer: return [(None, int(info[1][1]))]
        return {
            "primary": cisco_asa_state_names["%s" % params],
            "secondary": "standby",
            "failover_state": 1,
        }
    return params


def check_cisco_asa_failover(_no_item, params, parsed):
    converted_params = _convert_params(params)

    role = parsed["local"][0]
    status = parsed["local"][1]
    status_readable = cisco_asa_state_names[status]
    status_detail = parsed["local"][2]

    yield 0, "Device (%s) is the %s" % (role, status_detail)

    p_role = converted_params[role]
    if not p_role == status_readable:
        yield converted_params["failover_state"], \
              "(The %s device should be %s)" % (role, p_role)

    if not status in [ "9", "10" ]:
        yield 1, "Unhandled state %s reported" % status_readable


check_info["cisco_asa_failover"]  = {
    "parse_function"            : parse_cisco_asa_failover,
    "inventory_function"        : inventory_cisco_asa_failover,
    "check_function"            : check_cisco_asa_failover,
    "service_description"       : "Cluster Status",
    "snmp_scan_function"        : lambda oid: oid(".1.3.6.1.2.1.1.1.0").lower().startswith("cisco adaptive security") \
                                       or "cisco pix security" in oid(".1.3.6.1.2.1.1.1.0").lower(),
    "snmp_info"                 : (".1.3.6.1.4.1.9.9.147.1.2.1.1.1", [
                                             "2", # CISCO-FIREWALL-MIB::cfwHardwareInformation
                                             "3", # CISCO-FIREWALL-MIB::cfwHardwareStatusValue
                                             "4", # CISCO-FIREWALL-MIB::cfwHardwareStatusDetail
                                  ]),
    "group"                     : "cisco_asa_failover",
    "default_levels_variable"   : "cisco_asa_failover_default_levels",
}
