#!/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.
import cmk.base.plugins.agent_based.utils.sap_hana as sap_hana


def parse_sap_hana_replication_status(info):
    parsed = {}
    for sid_instance, lines in sap_hana.parse_sap_hana(info).items():
        inst = {}
        for line in lines:
            if line[0] == "mode:":
                inst["mode"] = line[1]
            elif line[0] == "systemReplicationStatus:":
                inst["sys_repl_status"] = line[1]
        if inst:
            parsed.setdefault(sid_instance, inst)
    return parsed


SAP_HANA_REPL_STATUS_MAP = {
    "0": (3, "unknown status from replication script", "state_unknown"),
    "10": (2, "no system replication", "state_no_replication"),
    "11": (2, "error", "state_error"),
    # "12" accuatly stands for "unknown replication status", but as per customer's information
    # (see SUP-1436), this should be indicated as "passive" replication aka secondary SAP HANA node.
    "12": (0, "passive", "state_replication_unknown"),
    "13": (1, "initializing", "state_initializing"),
    "14": (0, "syncing", "state_syncing"),
    "15": (0, "active", "state_active"),
}


def inventory_sap_hana_replication_status(parsed):
    for sid_instance, data in parsed.items():
        if data["sys_repl_status"] != "10" and (data.get("mode", "").lower() == "primary" or
                                                data.get("mode", "").lower() == "sync"):
            yield sid_instance, {}


@get_parsed_item_data
def check_sap_hana_replication_status(item, params, data):
    sys_repl_status = data["sys_repl_status"]
    state, state_readable, param_key = SAP_HANA_REPL_STATUS_MAP.get(
        sys_repl_status, (3, "unknown[%s]" % sys_repl_status, "state_unknown"))

    yield params.get(param_key, state), "System replication: %s" % state_readable


check_info['sap_hana_replication_status'] = {
    'parse_function': parse_sap_hana_replication_status,
    'inventory_function': inventory_sap_hana_replication_status,
    'check_function': check_sap_hana_replication_status,
    'service_description': 'SAP HANA Replication Status %s',
    'group': 'sap_hana_replication_status',
}
