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

# <<<mssql_clusters>>>
# MSSQL_VIM_SQLEXP node1 node1,node2


def inv_mssql_clusters(info):
    node = inv_tree_list("software.applications.mssql.instances:")

    def get_list_item(key, val):
        for item in node:
            if item[key] == val:
                return item

        node.append({})
        return node[-1]

    for line in info:
        if len(line) == 4:
            instance_id = line[0]
            active_node = line[2]
            nodes = line[3].split(",")
        elif len(line) == 3:
            # BD name may be ''
            instance_id = line[0]
            active_node = line[1]
            nodes = line[2].split(",")
        else:
            continue

        instance = get_list_item("name", instance_id)
        instance.update({
            "name": instance_id,
            "active_node": active_node,
            "node_names": ", ".join(nodes),
        })


inv_info["mssql_clusters"] = {
    "inv_function": inv_mssql_clusters,
}
