#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2016             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.


# single instance without config
# <<<postgres_instances>>>
# [[[postgres]]]
# 3717 /usr/lib/postgresql83/bin/postgres -D /var/lib/pgsql/data

# single instance with config
# <<<postgres_instances>>>
# 9792 /postgres/9.5.5/bin/postgres -D /postgres/CCENTERE

# multi instances with config
# <<<postgres_instances>>>
# 3960 /usr/lib/postgresql91/bin/postgres -D /var/lib/pgsql/bbtdb -p 5433
# 4149 /usr/lib/postgresql91/bin/postgres -D /var/lib/pgsql/conftdb -p 5434
# 16400 /usr/lib/postgresql91/bin/postgres -D /postgres/jiratdb


def parse_postgres_instances(info):
    parsed    = {}
    is_single = False
    for line in info:
        if line[0].startswith("[[[") and line[0].endswith("]]]"):
            db_id     = line[0][3:-3]
            is_single = True

        elif len(line) >= 4:
            if not is_single:
                db_id = line[3].split("/")[-1]
            parsed.setdefault(db_id.upper(), {"pid" : line[0]})

    return parsed


def inventory_postgres_instances(parsed):
    for db_id in parsed:
        yield db_id, None


def check_postgres_instances(item, params, parsed):
    if item in parsed:
        return 0, "Status: running with PID %s" % parsed[item]["pid"]
    return 2, "Instance %s not running" % item


check_info['postgres_instances'] = {
    'parse_function'      : parse_postgres_instances,
    'inventory_function'  : inventory_postgres_instances,
    'check_function'      : check_postgres_instances,
    'service_description' : 'PostgreSQL Instance %s',
}
