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

    Arguments:
    warn -- Warning as percent
    crit -- Critical as percent
    """
    stat = psutil.virtual_memory()

    pct_used = stat.percent

    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"])
    )

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

    ret[2] = f"total={stat.total}B"
    ret[2] += f" available={stat.available}B"
    ret[2] += f" percent={stat.percent}%"
    ret[2] += f" used={stat.used}B"
    ret[2] += f" free={stat.used}B"
    ret[2] += f" active={stat.active}B"
    ret[2] += f" inactive={stat.inactive}B"
    ret[2] += f" buffers={stat.buffers}B"
    ret[2] += f" cached={stat.cached}B"
    ret[2] += f" shared={stat.shared}B"
    ret[2] += f" slab={stat.slab}B"

    return ret
