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

# <<<kaspersky_av_client>>>
# Signatures 08.05.2015 01:23:00
# Fullscan 08.05.2015 05:43:16 0

# <<<kaspersky_av_client>>>
# Signatures 13.12.2016 11:55:00

factory_settings['kaspersky_av_client_default_levels'] = {
    'signature_age': (86400, 7 * 86400),
    'fullscan_age': (86400, 7 * 86400),
}


def parse_kaspersky_av_client(info):
    now = time.time()
    parsed = {}

    for line in info:
        if line[1] == 'Missing':
            continue

        date_text = line[1]
        time_text = line[2] if len(line) > 2 else "00:00:00"
        # We assume that the timestamp is to be interpreted in the timezone of
        # the Checkmk server. This might be a problem, if e.g. the agent is located
        # in China and the Checkmk server in USA.
        age = now - time.mktime(time.strptime(f"{date_text} {time_text}", '%d.%m.%Y %H:%M:%S'))

        if line[0] == "Signatures":
            parsed['signature_age'] = age

        elif line[0] == "Fullscan":
            parsed['fullscan_age'] = age

            # handle state of last fullscan if provided
            if len(line) == 4:
                parsed['fullscan_failed'] = line[3] != "0"

    return parsed


def inventory_kaspersky_av_client(parsed):
    return [(None, {})]


def check_kaspersky_av_client(_no_item, params, parsed):
    for key, what in [
        ("signature_age", "Last update of signatures"),
        ("fullscan_age", "Last fullscan"),
    ]:
        age = parsed.get(key)
        if age is None:
            yield 3, what + ": unknown"
        else:
            warn, crit = params[key]
            if age >= crit:
                state = 2
            elif age >= warn:
                state = 1
            else:
                state = 0

            infotext = "%s %s ago" % (what, get_age_human_readable(age))
            if state > 0:
                infotext += " (warn/crit at %s/%s)" % (get_age_human_readable(warn),
                                                       get_age_human_readable(crit))

            yield state, infotext

    if parsed.get("fullscan_failed"):
        yield 2, "Last fullscan failed"


check_info['kaspersky_av_client'] = {
    'parse_function': parse_kaspersky_av_client,
    'inventory_function': inventory_kaspersky_av_client,
    'check_function': check_kaspersky_av_client,
    'service_description': 'Kaspersky AV',
    'default_levels_variable': 'kaspersky_av_client_default_levels',
    'group': 'kaspersky_av_client',
}
