#!/usr/bin/env python3
# ***************************************************************************
#  IIIIII NNN  NNN  Copyright (C) 2022 Innovative Networks, Inc.
#    II    NNN  N   All Rights Reserved. Any redistribution or reproduction
#    II    N NN N   of part or all of the content of this program in any form
#    II    N  NNN   without expressed written consent of the copyright holder
#  IIIIII NNN  NNN  is strictly prohibited.  Please contact admins@in-kc.com
#   Be Innovative.  for additional information.
# ***************************************************************************
#  check_load.py
#  Author - Ian Perry <iperry@indigex.com>
#
#  Purpose:  Checks load on macos
#
#  Version History:
#       2023.05.10 - Initial creation
# ***************************************************************************

try:
    from inmon_utils import *
except:
    import sys

    print("Unable to import inmon utils")
    sys.exit(3)

# Installs psutil if it's not there.
ensure_module(psutil)


def check_load(config):
    """Check CPU load.

    Arguments:
    warn -- Warning in 1:5:15 format
    crit -- Critical in 1:5:15 format
    """
    # If there are less than 2 colons, input is invalid
    if config["crit"].count(":") != 2:
        print("Critical must be in format 1:5:15")
        sys.exit(3)
    else:
        # Format values as float into an array
        crit = [float(i) for i in config["crit"].split(":")]

    if config["warn"].count(":") != 2:
        print("Warning must be in format 1:5:15")
        sys.exit(3)
    else:
        warn = [float(i) for i in config["warn"].split(":")]

    # This checks if all warning values are <= their respective critical values.
    if not all([w <= c for w, c in zip(warn, crit)]):
        print(
            "All warning values must be less than or equal to their counterpart critical values."
        )
        sys.exit(3)

    stat = [round(x, 2) for x in psutil.getloadavg()]

    # If any value is greater than or equal to its crit counterpart
    if any([x >= y for x, y in zip(stat, crit)]):
        ret = [
            2,
            f"[CRIT] - Load average critical, {', '.join([str(x) for x in stat])}",
        ]

    # If any value is greater or equal to warn but less than crit
    elif any([w <= x < c for w, x, c in zip(warn, stat, crit)]):
        ret = [1, f"[WARN] - Load average high, {', '.join([str(x) for x in stat])}"]

    # If all values are lower than warn but greater than 0
    elif all([0 < x < w for x, w in zip(stat, warn)]):
        ret = [0, f"[OK] - Load average nominal, {', '.join([str(x) for x in stat])}"]

    # Something has gone wrong, throw an error.
    else:
        ret = [3, f"[UNKN] - An unknown error occurred."]

    # Return the text and perfdata, exit with code.
    ret[2] = f"load_1={stat[0]}
    ret[2] += f" load_5={stat[1]}
    ret[2] += f" load_15{stat[2]}"

    return ret
