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


def inventory_synology_disks(info):
    for disk, model, status, _temperature in info:
        # SSD used as cache are "not initialized". We remember that
        # here.
        if "SSD" in model and status == "3":
            params = {"used_as_cache": True}
        else:
            params = {}

        yield disk, params


def check_synology_disks(item, params, info):
    states = {
        1: (0, "OK"),
        2: (0, "OK"),
        3: (1, "not initialized"),
        4: (2, "system partition failed"),
        5: (2, "crashed"),
    }

    if params is None:
        params = {}

    for disk, model, status, temperature in info:
        if disk == item:
            temp = int(temperature)
            if status == "3" and params.get("used_as_cache"):
                status_text = "used as cache"
                status_code = 0
            else:
                status_code, status_text = states[int(status)]

            message = "Status: %s, Temperature: %d °C, Model: %s" % (status_text, temp, model)
            return status_code, message, [("temp", temp)]


check_info["synology_disks"] = {
    "check_function": check_synology_disks,
    "inventory_function": inventory_synology_disks,
    "service_description": "Disk %s",
    "has_perfdata": True,
    "snmp_scan_function": synology_scan_function,
    "snmp_info": (
        ".1.3.6.1.4.1.6574.2.1.1",
        [
            2,  # SYNOLOGY-DISK-MIB::diskID
            3,  # SYNOLOGY-DISK-MIB::diskModel
            5,  # SYNOLOGY-DISK-MIB::diskStatus
            6,  # SYNOLOGY-DISK-MIB::diskTemperature
        ],
    ),
}
