#!/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_cpu.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_cpu(config):
    """Check CPU usage.

    Arguments:
    config -- object in form of:
    {'check_cpu': {'crit': val, 'warn', val}}
    """
    stat = psutil.cpu_times_percent()  # Retrieve CPU statistics
    pct_used = 100 - stat.idle  # Convert to a percentage

    # Process crit and warn variables
    crit = (
        float(config["crit"].replace("%", ""))
        if "%" in config["crit"]
        else float(config["crit"])
    )
    warn = (
        float(config["warn"].replace("%", ""))
        if "%" in config["warn"]
        else float(config["warn"])
    )

    # Process calculation
    if pct_used >= crit:
        ret = [2, f"[CRIT] - CPU usage critical: {pct_used}%"]
    elif crit > pct_used >= warn:
        ret = [1, f"[WARN] - CPU usage high: {pct_used}%"]
    elif warn > pct_used:
        ret = [0, f"[OK] - CPU usage nominal: {pct_used}%"]
    else:
        ret = [3, f"[UNKN] - Unknown error occurred."]

    # Add performance data to output
    ret[2] = f"user={stat.user}%"
    ret[2] += f" nice={stat.nice}%"
    ret[2] += f" system={stat.system}%"
    ret[2] += f" idle={stat.idle}%"

    # Return tuple
    return ret
