#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.synology import *  # pylint: disable=wildcard-import,unused-wildcard-import

factory_settings["synology_update_levels"] = {
    "ok_states": [2],
    "warn_states": [5],
    "crit_states": [1, 4],
}


def inventory_synology_update(info):
    return [(None, {})]


def check_synology_update(_no_item, params, info):
    states = {
        1: "Available",
        2: "Unavailable",
        3: "Connection",
        4: "Disconnected",
        5: "Others",
    }
    version, device_state = info[0]
    device_state = int(device_state)
    state = 3
    if device_state in params["ok_states"]:
        state = 0
    elif device_state in params["warn_states"]:
        state = 1
    elif device_state in params["crit_states"]:
        state = 2
    elif device_state == 3:
        # to prevent flapping between update avail and Connection
        raise MKCounterWrapped("Devices try to connect to the update server")
    return state, "Update Status: %s, Current Version: %s" % (states[device_state], version)


check_info["synology_update"] = {
    "check_function": check_synology_update,
    "inventory_function": inventory_synology_update,
    "service_description": "Update",
    "snmp_scan_function": synology_scan_function,
    "snmp_info": (
        ".1.3.6.1.4.1.6574.1.5",
        [
            3,  # Version
            4,  # Status
        ],
    ),
    "default_levels_variable": "synology_update_levels",
    "group": "synology_update",
}
