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

# <<<hyperv_checkpoints>>>
# Has_Checkpoints
# f5689086-243b-4dfe-9775-571ef6be8a1b 2063
# c85ae17b-1a6c-4a34-949a-a1b9385ef67a 2040


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


def check_hyperv_checkpoints(item, params, info):
    snapshots = []
    for line in info:
        if len(line) != 2:
            continue
        snapshots.append((line[0], int(line[1])))

    if snapshots:
        yield 0, "%s checkpoints" % len(snapshots)

        # We assume that the last snapshot is the last line
        # of the agent output
        for title, key, snapshot in [
            ("Oldest", "age_oldest", max(snapshots, key=lambda x: x[1])),
            ("Last", "age", snapshots[-1]),
        ]:
            name, age = snapshot
            infotext = "%s: %s (%s)" % (title, get_age_human_readable(age), name)
            warn, crit = params.get(key, (None, None))
            if crit is not None and age >= crit:
                state = 2
            elif warn is not None and age >= warn:
                state = 1
            else:
                state = 0
            if state:
                infotext += " (warn/crit at %s/%s)" % (
                    get_age_human_readable(warn),
                    get_age_human_readable(crit),
                )
            yield state, infotext, [(key, age, warn, crit)]
    else:
        yield 0, "No Checkpoints found"


check_info["hyperv_checkpoints"] = {
    "check_function": check_hyperv_checkpoints,
    "inventory_function": inventory_hyperv_checkpoints,
    "service_description": "HyperV Checkpoints",
    "group": "vm_snapshots",
    "has_perfdata": True,
}
