#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# pylint: disable=broad-exception-raised,invalid-name,global-variable-undefined,consider-using-with
"""
zpool check script for use with Nagios
Copyright 2026 - Mark Schouten <mark@tuxis.nl>

Inspired by http://soren.klintrup.dk/zpool/

# Copyright 2026, Mark Schouten <mark@tuxis.nl>, Tuxis B.V.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""

import sys
import re
import subprocess
import argparse

# Nagios exit codes
EXIT_CODES = {
    'OK': 0,
    'WARNING': 1,
    'CRITICAL': 2,
    'UNKNOWN': 3
}

ZPOOL_COMMAND='/sbin/zpool'

def get_output(command):
    """Execute the command and return all the output"""
    if args.debug:
        print(f"Executing {command}")

    p = subprocess.Popen(command.split(' '),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    output, err = p.communicate()

    if err:
        raise Exception(err.decode())

    return output.decode()


def list_zpools():
    """Get a list of all the zpools"""
    zpools = []

    for l in get_output(f"{args.exe} list -H -o name").split('\n'):
        if l:
            zpools.append(l)

    return zpools

def check_health(zpool):
    """Check the health status of a pool"""

    state = get_output(f"{args.exe} list -H -o health {zpool}").rstrip()

    return state

def check_capacity(zpool):
    """Check the capacity of a pool"""

    capacity = int(get_output(f"{args.exe} list -H -p -o cap {zpool}").rstrip())

    if capacity > args.critical:
        return ("CRITICAL", capacity)

    if capacity > args.warn:
        return ("WARNING", capacity)

    return ("OK", capacity)

def check_special_capacity(zpool):
    """Check the capacity of a special vdev in a pool"""

    poolinfo = get_output(f"{args.exe} list -v -H -p {zpool}")

    vdevs = []

    PARSINGSPECIAL=False
    for l in poolinfo.split("\n"):
        if l.startswith('special'):
            PARSINGSPECIAL=True
            continue
        if PARSINGSPECIAL:
            if not re.match(r'\s', l):
                PARSINGSPECIAL=False
                continue

        if PARSINGSPECIAL:
            if l.split()[7] != '-':
                vdev = l.split()[0]
                capacity = int(l.split()[7])
                if capacity> args.critical:
                    vdevs.append((vdev, "WARNING", capacity))
                else:
                    vdevs.append((vdev, "OK", capacity))

    return vdevs

def main():
    """The main loop"""
    # parse args
    parser = argparse.ArgumentParser(description='Tuxis zpool monitoring plugin.')
    parser.add_argument('-e','--exe',
        help=f'zpool executable {ZPOOL_COMMAND}',
        nargs='?',
        default=ZPOOL_COMMAND,
        type=str)
    parser.add_argument('-w','--warn',
        help='Issue WARNING at this percentage of usage',
        nargs='?',
        default=80,
        type=int)
    parser.add_argument('-c','--critical',
        help='Issue CRITICAL at this percentage of usage',
        nargs='?',
        default=90,
        type=int)
    parser.add_argument('-d','--debug',
        action='store_true',
        help='Show debug information')
    parser.add_argument('--exclude-special',
        help='Exclude special devices from check',
        nargs='?',
        const=True,
        default=False,
        type=lambda x: (x.lower() in ("yes", "true", "y", "1")))
    global args
    args = parser.parse_args()

    STATE="OK"
    RETMSG=[]

    zpools = list_zpools()

    for zpool in zpools:
        health=check_health(zpool)
        if health != "ONLINE":
            RETMSG.insert(0, f"{zpool} is not healthy: {health}")
            STATE="CRITICAL"
        else:
            RETMSG.append(f"{zpool} is healthy: {health}")

        (capstate, capacity) = check_capacity(zpool)
        if EXIT_CODES[capstate]  > EXIT_CODES[STATE]:
            STATE=capstate

        if EXIT_CODES[capstate] != 0:
            RETMSG.insert(0, f"{zpool} capacity at {capacity}%")
        else:
            RETMSG.append(f"{zpool} capacity at {capacity}%")

        if not args.exclude_special:
            for special in check_special_capacity(zpool):
                if EXIT_CODES[special[1]]  > EXIT_CODES[STATE]:
                    STATE=special[1]
                if EXIT_CODES[special[1]] != 0:
                    RETMSG.insert(0, f"Special {zpool}/{special[0]} capacity at {special[2]}%")
                else:
                    RETMSG.append(f"Special {zpool}/{special[0]} capacity at {special[2]}%")


    msg = ' | '.join(RETMSG)
    print(f'{STATE}: {msg}')
    return EXIT_CODES[STATE]

if __name__ == "__main__":
    sys.exit(main())
