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

# Based on check from  Darin Perusich <darin@darins.net>
#
# /usr/sbin/zpool status -x
#
# Example output of a healthy spool
# ---------------------------------
# all pools are healthy
# ---------------------------------
#
# Example output with no poole
# ---------------------------------
# no pools available
# ---------------------------------
#
# Example output of a pool with a error
# ---------------------------------
# pool: snapshots
#  state: ONLINE
# status: One or more devices has experienced an unrecoverable error.  An
#         attempt was made to correct the error.  Applications are unaffected.
# action: Determine if the device needs to be replaced, and clear the errors
#         using 'zpool clear' or replace the device with 'zpool replace'.
#    see: http://www.sun.com/msg/ZFS-8000-9P
#  scrub: none requested
# config:
#
#         NAME        STATE     READ WRITE CKSUM
#         snapshots   ONLINE       0     0     0
#           raidz1    ONLINE       0     0     0
#             c0d0s7  ONLINE       0     0     0
#             c0d1s7  ONLINE       0     0     0
#             c1d0s7  ONLINE       0     0     0
#             c1d1s7  ONLINE       0     0     1
#
# errors: No known data errors
# ---------------------------------


def inventory_zpool_status(info):
    if not info or " ".join(info[0]) == "no pools available":
        return []
    return [(None, None)]


def check_zpool_status(_no_item, _no_params, info):
    if " ".join(info[0]) == "all pools are healthy":
        return 0, "All pools are healthy"
    elif " ".join(info[0]) == "no pools available":
        return 3, "No pools available"

    start_pool = False
    multiline = False
    last_pool = None
    error_pools = {}
    warning_pools = {}
    pool_messages = {}
    message = []
    state = 0

    for line in info:
        if line[0] == "pool:":
            last_pool = line[1]
            pool_messages.setdefault(last_pool, [])
            continue

        if line[0] == "state:":
            if line[1] == "ONLINE":
                state = 0
            elif line[1] == "DEGRADED":
                state = 1
                message.append("DEGRADED State")
            elif line[1] == "FAULTED":
                state = 2
                message.append("FAULTED State")
            elif line[1] == "UNAVIL":
                state = 2
                message.append("UNAVIL State")
            elif line[1] == "REMOVED":
                state = 2
                message.append("REMOVED State")
            elif line[1] == "OFFLINE":
                state = 0
            else:
                message.append("Unknown State")
                state = 1
            continue

        if line[0] in ["status:", "action:"]:
            pool_messages[last_pool].append(" ".join(line[1:]))
            multiline = True
            continue

        if line[0] in ["scrub:", "see:", "scan:", "config:"]:
            multiline = False
            continue

        if line[0] == "NAME":
            multiline = False
            start_pool = True
            continue

        if line[0] == "errors:":
            multiline = False
            start_pool = False
            msg = " ".join(line[1:])
            if msg != 'No known data errors':
                pool_messages[last_pool].append(msg)
            continue

        if line[0] in ["spares", "logs", "cache"]:
            start_pool = False
            continue

        if start_pool is True:
            if line[1] != "ONLINE":
                error_pools[line[0]] = tuple(line[1:])
                continue

            if saveint(line[4]) != 0:
                warning_pools[line[0]] = tuple(line[1:])
                continue

        if multiline:
            pool_messages[last_pool].append(" ".join(line))
            continue

    for pool, msg in pool_messages.items():
        state = 1
        message.append("%s: %s" % (pool, " ".join(msg)))

    for pool, msg in warning_pools.items():
        state = 1
        message.append("%s CKSUM: %d" % (pool, saveint(msg[3])))

    for pool, msg in error_pools.items():
        state = 2
        message.append("%s state: %s" % (pool, msg[0]))

    if len(message) == 0:
        message = ['No critical errors']

    return state, ", ".join(message)


check_info["zpool_status"] = {
    'check_function': check_zpool_status,
    'inventory_function': inventory_zpool_status,
    'service_description': 'zpool status',
    'group': 'zpool_status',
}
