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

# We use the following OIDs:

# PowerNet-MIB::upsAdvTestDiagnosticsResults   .1.3.6.1.4.1.318.1.1.1.7.2.3
# upsAdvTestDiagnosticsResults OBJECT-TYPE
#         SYNTAX INTEGER {
#                 ok(1),
#                 failed(2),
#                 invalidTest(3),
#                 testInProgress(4)
#         }
#         ACCESS read-only
#         STATUS mandatory
#         DESCRIPTION
#                 "The results of the last UPS diagnostics test performed."
#         ::= { upsAdvTest 3 }

# PowerNet-MIB::upsAdvTestLastDiagnosticsDate  .1.3.6.1.4.1.318.1.1.1.7.2.4
# upsAdvTestLastDiagnosticsDate OBJECT-TYPE
#         SYNTAX DisplayString
#         ACCESS read-only
#         STATUS mandatory
#         DESCRIPTION
#                 "The date the last UPS diagnostics test was performed in
#                  mm/dd/yy format."
#         ::= { upsAdvTest 4 }
#

ups_test_default = (0, 0)


def check_apc_test(item, params, info):
    days_warn, days_crit = params
    if not info:
        return 3, "Data Missing"
    last_result = int(info[0][0])
    last_date = info[0][1]

    if last_date == 'Unknown' or len(last_date) not in [8, 10]:
        return 3, "Date of last self test is unknown"

    year_format = '%y' if len(last_date) == 8 else '%Y'
    last_ts = time.mktime(time.strptime(last_date, '%m/%d/' + year_format))
    days_diff = (time.time() - last_ts) / 86400.0

    diagnostic_status_text = {1: "OK", 2: "failed", 3: "invalid", 4: "in progress"}

    state = 0
    diag_label = ""
    if last_result == 2:
        state = 2
        diag_label = "(!!)"
    elif last_result == 3:
        state = 1
        diag_label = "(!)"

    time_label = ""
    if days_crit and days_diff >= days_crit:
        state = 2
        time_label = "(!!)"
    elif days_warn and days_diff >= days_warn:
        state = max(state, 1)
        time_label = "(!)"

    return state, "Result of self test: %s%s, Date of last test: %s%s" % \
            (diagnostic_status_text.get(last_result, '-'), diag_label, last_date, time_label)


def inventory_apc_test(info):
    if info:
        return [(None, "ups_test_default")]


check_info['apc_symmetra_test'] = {
    "inventory_function": inventory_apc_test,
    "check_function": check_apc_test,
    "service_description": "Self Test",
    "group": "ups_test",
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.318.1.3"),
    "snmp_info": (".1.3.6.1.4.1.318.1.1.1.7.2", [3, 4])
}
