#!/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.stormshield import *  # pylint: disable=wildcard-import,unused-wildcard-import


def inventory_stormshield_services(info):
    for name, state, _uptime in info:
        if state == '1':
            yield name, {}


def check_stormshield_services(item, params, info):
    service_state = {'0': 'down', '1': 'up'}
    for name, state, uptime in info:
        if name == item:
            m, s = divmod(int(uptime), 60)
            h, m = divmod(m, 60)
            d, h = divmod(h, 24)
            perfdata = [('uptime', int(uptime))]
            if state == '0':
                yield 1, 'Service %s is %s' % (name, service_state[state])
            elif state == '1':
                yield 0, 'Service %s is %s for %d days, %dh:%02dm:%02ds' % (
                    name, service_state[state], d, h, m, s), perfdata
            else:
                yield 3, 'Check doesnt work as expected'


check_info['stormshield_services'] = {
    'default_levels_variable': 'stormshield_services_default_levels',
    'inventory_function': inventory_stormshield_services,
    'check_function': check_stormshield_services,
    'service_description': 'Service %s',
    'has_perfdata': True,
    'snmp_info': (
        '.1.3.6.1.4.1.11256.1.7.1.1',
        [
            '2',  # snsServicesName
            '3',  # snsServicesState
            '4'  # snsServicesUptime
        ]),
    'snmp_scan_function': stormshield_scan_function,
}
