#!/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_disk.py
#  Author - Ian Perry <iperry@indigex.com>
#
#  Purpose:  Checks disk on macos
#
#  Version History:
#       2023.05.09 - Initial creation
# ***************************************************************************


try:
    from inmon_utils import *
except:
    import sys

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

import shutil


def check_disk(config):
    """Check disk usage.

    Arguments:
    warn -- Warning as percent
    crit -- Critical as percent
    """
    stat = shutil.disk_usage("/")  # Get disk usage

    pct_free = (stat.free / stat.total) * 100  # Calculate percent free

    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 data
    if pct_free <= crit:
        ret = [2, f"[CRIT] - Disk at {round(pct_free, 1)}% free space"]
    elif crit < pct_free <= warn:
        ret = [1, f"[WARN] - Disk at {round(pct_free, 1)}% free space"]
    elif warn < pct_free:
        ret = [0, f"[OK] - Disk at {round(pct_free, 1)}% free space"]
    else:
        ret = [3, f"[UNKN] - Unknown error occurred."]

    # Append perfdata
    ret[2] = f"total={stat.total}B"
    ret[2] += f" free={stat.free}B"
    ret[2] += f" used={stat.used}B"

    # Return tuple
    return ret
