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

# Example output:
# <<<vxvm_objstatus>>>
# v datadg lalavol CLEAN DISABLED
# v datadg oravol ACTIVE ENABLED
# v datadg oravol-L01 ACTIVE ENABLED
# v datadg oravol-L02 ACTIVE ENABLED
# v testgroup oravol-L02 ACTIVE ENABLED


def vxvm_objstatus_disks(info):
    groups = {}
    found_groups = []
    for dg_type, dg_name, name, admin_state, kernel_state in info:
        if dg_type == "v":
            if dg_name not in found_groups:
                groups[dg_name] = [(name, admin_state, kernel_state)]
                found_groups.append(dg_name)
            else:
                groups[dg_name].append((name, admin_state, kernel_state))
    return groups


def inventory_vxvm_objstatus(info):
    return list(vxvm_objstatus_disks(info).items())


def check_vxvm_objstatus(item, params, info):
    groups = vxvm_objstatus_disks(info)
    volumes = groups.get(item)
    if volumes is not None:
        state = 0
        messages = []
        for volume, admin_state, kernel_state in volumes:
            text = []
            error = False
            if admin_state != "CLEAN" and admin_state != "ACTIVE":
                state = 2
                text.append("%s: Admin state is %s(!!)" % (volume, admin_state))
                error = True
            if kernel_state != "ENABLED" and kernel_state != "DISABLED":
                state = 2
                text.append("%s: Kernel state is %s(!!)" % (volume, kernel_state))
                error = True
            if error is False:
                text = ["%s: OK" % volume]
            messages.append(", ".join(text))
        return (state, ", ".join(messages))

    return (2, "Group not found")


check_info["vxvm_objstatus"] = {
    "check_function": check_vxvm_objstatus,
    "inventory_function": inventory_vxvm_objstatus,
    "service_description": "VXVM objstatus %s",
}
