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

# <<<db2_backup>>>
# [[[db2taddm:CMDBS1]]]
# 2015-03-12-04.00.13.000000

db2_backup_default_levels = (86400 * 14, 86400 * 28)


def inventory_db2_backup(parsed):
    for instance in parsed[1]:
        yield instance, "db2_backup_default_levels"


def check_db2_backup(item, params, parsed):
    db = parsed[1].get(item)
    if not db:
        raise MKCounterWrapped("Login into database failed")

    try:
        last_backup = time.mktime(time.strptime(db[0][0][:19], "%Y-%m-%d-%H.%M.%S"))
    except Exception:
        if db[0][0] == "-":
            yield 1, "No backup available"
        else:
            yield 3, "Last backup contains an invalid timestamp: %s" % db[0][0]
        return

    age = time.time() - last_backup
    if params:
        warn, crit = params
        if age >= crit:
            yield 2, "Time since last backup: %s" % get_age_human_readable(age)
        elif age >= warn:
            yield 1, "Time since last backup: %s" % get_age_human_readable(age)
        else:
            yield 0, "Time since last backup: %s" % get_age_human_readable(age)
    else:
        yield 0, "Time since last backup: %s" % get_age_human_readable(age)


check_info["db2_backup"] = {
    "parse_function": parse_db2_dbs,
    "service_description": "DB2 Backup %s",
    "check_function": check_db2_backup,
    "inventory_function": inventory_db2_backup,
    "group": "db2_backup",
}
