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

# <<<postgres_stat_database>>>
# datid datname numbackends xact_commit xact_rollback blks_read blks_hit tup_returned tup_fetched tup_inserted tup_updated tup_deleted
# 1 template1 0 0 0 0 0 0 0 0 0 0
# 11563 template0 0 0 0 0 0 0 0 0 0 0
# 11564 postgres 2 568360 17 811 8855508 157949341 879922 0 0 0
# 16385 foobardb 7 43619118 262 3589 838098632 854602076 441785363 8298 602481 2806


def parse_postgres_stat_database(info):
    if len(info) == 0:
        return {}
    parsed = {}
    instance_name = ""
    for line in info:
        if line[0].startswith("[[[") and line[0].endswith("]]]"):
            instance_name = line[0][3:-3].upper()
            continue
        if line[0] == "datid" and line[1] == "datname":
            headers = line
            continue
        # All values other than datid and datname must be int
        row = {
            k: int(v) if v else v for k, v in zip(headers, line) if k not in ("datid", "datname")
        }
        # datid should be an oid, which should be an int, but that may not be guaranteed
        # when the data entry is empty, we keep it as empty. Might have to change this to a default value (0) if issues come up.
        row["datid"] = line[0]
        datname = (
            line[1] if line[1] else "access_to_shared_objects"
        )  # https://www.postgresql.org/message-id/CABUevEzMHzdAQjvpWO6eGSZeg8FKmLLPhdwVoqaOXR8VWnyd8w%40mail.gmail.com
        if instance_name:
            db_name = "%s/%s" % (instance_name, datname)
        else:
            db_name = datname

        parsed[db_name] = row

    return parsed


# Create a check for all databases that have seen at least
# one commit in their live.
def inventory_postgres_stat_database(parsed):
    return [(k, {}) for k in parsed if parsed[k]["xact_commit"] > 0]


def check_postgres_stat_database(item, params, parsed):
    if item not in parsed:
        return (3, "Database not found")

    stats = parsed[item]
    status = 0
    infos = []
    perfdata = []
    this_time = time.time()
    for what, title in [
        ("blks_read", "Blocks Read"),
        ("tup_fetched", "Fetches"),
        ("xact_commit", "Commits"),
        ("tup_deleted", "Deletes"),
        ("tup_updated", "Updates"),
        ("tup_inserted", "Inserts"),
    ]:
        rate = get_rate("postgres_stat_database.%s.%s" % (item, what), this_time, stats[what])
        infos.append("%s: %.2f/s" % (title, rate))
        if what in params:
            warn, crit = params[what]
            if rate >= crit:
                status = 2
                infos[-1] += "(!!)"
            elif rate >= warn:
                status = max(status, 1)
                infos[-1] += "(!)"
        else:
            warn, crit = None, None
        perfdata.append((what, rate, warn, crit))
    return (status, ", ".join(infos), perfdata)


check_info["postgres_stat_database"] = {
    "parse_function": parse_postgres_stat_database,
    "inventory_function": inventory_postgres_stat_database,
    "check_function": check_postgres_stat_database,
    "service_description": "PostgreSQL DB %s Statistics",
    "has_perfdata": True,
    "group": "postgres_stat_database",
}


def check_postgres_stat_database_size(item, _no_params, parsed):
    if item not in parsed:
        # In case of missing information we assume that the login into
        # the database has failed and we simply skip this check. It won't
        # switch to UNKNOWN, but will get stale.
        raise MKCounterWrapped("Login into database failed")

    stats = parsed[item]
    size = stats["datsize"]

    if size in ["", None]:
        yield (1, "Database size is not available.")
        return

    yield (0, "Size is %s" % get_bytes_human_readable(size), [("size", size)])


check_info["postgres_stat_database.size"] = {
    "check_function": check_postgres_stat_database_size,
    "inventory_function": inventory_postgres_stat_database,
    "service_description": "PostgreSQL DB %s Size",
    "has_perfdata": True,
}
