#!/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_ntp.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 platform
import subprocess

ensure_module("ntplib")


def get_default_gateway_ipv4():
    """Get ipv4 address of default gateway"""
    os = platform.system()
    if os == "Windows":
        stat = subprocess.run(["ipconfig"], capture_output=True)
        output = stat.stdout.decode().split("\r\n")
        output = [x.strip() for x in output if x != ""]
        output = [
            x.replace(" .", "") for x in output if x.startswith("Default Gateway")
        ]
        output = [x.split(":") for x in output]
        for entry in output:
            if entry[1] != "":
                return entry[1].strip()
        return None
    if os == "Linux":
        stat = subprocess.run(["ip", "route", "show"], capture_output=True)
        output = stat.stdout.decode().split("\n")
        return output[0].split()[2]
    if os == "macOS":
        stat = subprocess.run(["route", "-n", "get", "default"], capture_output=True)
        output = stat.stdout.decode().split("\n")
        output = next(
            (x.strip() for x in output if x.strip().startswith("gateway")), None
        )
        return output.split(": ")[1]


def check_ntp(config):
    """Check NTP time offset."""
    ntp_client = ntplib.NTPClient()
    gateway = get_default_gateway_ipv4()
    if gateway is None:
        return [3, f"[UNKN] - Device has no default gateway", None]
    response = c.request(gateway)
    offset = response.offset
    if abs(offset) >= 60:
        return [2, f"[CRIT] - NTP offset critical {offset} | offset={offset}", None]
    elif 60 > abs(offset) >= 30:
        return [1, f"[WARN] - NTP offset warning {offset} | offset={offset}", None]
    elif 30 > abs(offset):
        return [0, f"[OK] - NTP offset OK {offset} | offset={offset}", None]
    else:
        return [3, f"[UNKN] - An unknown error occurred.", None]
