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

# 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 subprocess
import argparse
import json

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

PBS_COMMAND = '/usr/sbin/proxmox-backup-manager'

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_datastores():
    """Get a list of all the datastores"""
    datastores = []

    for ds in json.loads(get_output(f"{args.exe} datastore list --output-format=json")):
        datastores.append(ds)

    return datastores

def check_maintenance_mode(ds):
    """Check the maintenance mode of a datastore"""

    if 'maintenance-mode' in ds:
        if ds['maintenance-mode'] == 'read-only':
            return 1

        if ds['maintenance-mode'] == 'offline' and args.strict is True:
            return 1

    return 0

def main():
    """The main loop"""
    # parse args
    parser = argparse.ArgumentParser(description='Tuxis zpool monitoring plugin.')
    parser.add_argument('-e','--exe',
        help=f'proxmox-backup-manager executable {PBS_COMMAND}',
        nargs='?',
        default=PBS_COMMAND,
        type=str)
    parser.add_argument('-s','--strict',
        help='Issue WARNING if there are offline datastores too',
        action='store_true')
    parser.add_argument('-d','--debug',
        action='store_true',
        help='Show debug information')
    global args
    args = parser.parse_args()

    STATE="OK"
    RETMSG=[]

    for datastore in list_datastores():
        if check_maintenance_mode(datastore):
            RETMSG.insert(0, f"{datastore['name']} is in {datastore['maintenance-mode']} mode")
            STATE="WARNING"

    if STATE == "OK":
        if not args.strict:
            RETMSG.append("All datastores are either online, or in offline mode")
        else:
            RETMSG.append("All datastores are online")

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

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