#!/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_all.py
#  Author - Ian Perry <iperry@indigex.com>
#
#  Purpose:  Runs all check commands for macOS
#
#  Version History:
#       2023.05.30 - Initial creation
# ***************************************************************************

try:
    from inmon_utils import *
except:
    import sys

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

import os

# YAML used for config files
ensure_module("yaml", "PyYAML")

# If config file isn't there, die.
if not os.path.isfile(os.path.join(os.getcwd(), ".config.yml")):
    print("Config file doesn't exist.")
    sys.exit(3)

# Load original config
with open(os.path.join(os.getcwd(), ".config.yml"), "r") as f:
    config = yaml.safe_load(f)

# Load override if it exists.
if os.path.isfile(os.path.join(os.getcwd(), ".override.yml")):
    with open(os.path.join(os.getcwd(), ".override.yml"), "r") as f:
        override_config = yaml.safe_load(f)
    dict_merge(config, override_config)

# Initialize variables
check_results = []

# Create session to use across all checks.
session = create_request_session()

# Cycle through all checks in config file.
for check in config[check_config].keys():
    # Programatically import check module
    module = __import__(check)

    # Define check function programatically
    check_function = getattr(module, check)

    # Run check
    result = check_function()

    hostname = (
        socket.getfqdn()
        if config["running_config"]["hostname"] is None
        else config["running_config"]["hostname"]
    )

    # Create passive result
    passive_result = PassiveCheckResult(
        parent="parent",
        host=hostname,
        service=config[check]["service_name"],
        exit_status=result[0],
        plugin_output=result[1],
        performance_data=result[2],
        check_source=socket.getfqdn(),
    )

    # Submit passive result using session created earlier.
    passive_result.submit(session)
