#!/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_version>>>
# PostgreSQL 9.3.6 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit
#
# # instance
# <<<postgres_version>>>
# [[[foobar]]]
# PostgreSQL 9.3.6 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit
#
# # In case the server has been stopped:
# <<<postgres_version:sep(1)>>>
#
# psql: could not connect to server: No such file or directory
#     Is the server running locally and accepting
#     connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5437"?
#


def parse_postgres_version(info):
    parsed = {}
    instance_name = ""
    for line in info:
        if line[0].startswith("[[[") and line[0].endswith("]]]"):
            instance_name = line[0][3:-3]
            continue
        parsed.setdefault(instance_name, " ".join(line))
    return parsed


@get_parsed_item_data
def check_postgres_version(_no_item, _no_params, data):
    if "could not connect" in data:
        raise MKCounterWrapped("Login into database failed")
    yield 0, data


check_info["postgres_version"] = {
    "parse_function": parse_postgres_version,
    "inventory_function": discover(),
    "check_function": check_postgres_version,
    "service_description": "PostgreSQL Version %s",
}
