#!/usr/bin/python3

'''
Usage: check_timesync [-H hostname] [-w warning_seconds] [-c critical_seconds]
'''

import sys
import time
import os
import getopt

try:
    opts, files = getopt.gnu_getopt(sys.argv[1:], 'H:w:c:C:d', [])
    argv = dict(opts)
except getopt.GetoptError as err:
    print("Error: %s" % err)
    sys.exit(1)

hostname = argv.get("-H")
nrpe_command = argv.get("-C", "check_timesync")
crit_time = float(argv.get("-c", 3))
warn_time = float(argv.get("-w", 1))
debug = "-d" in argv

if hostname:
    try:
        plugin_dir = os.path.dirname(sys.argv[0])
        nrpe = os.popen(
            f"{plugin_dir}/check_nrpe -H {hostname} -c {nrpe_command}"
        )
        output = nrpe.read().replace("\n", " ").strip()
        if debug:
            print(output)
        retcode = (nrpe.close() or 0)>>8
        if retcode>0 or not output.startswith("TimeSync OK - "):
            print(f"TimeSync ERROR - {output}")
            sys.exit(2)
        ra = {}
        for part in output.strip().split(", "):
            if part.startswith("warn="):
                warn_time = float(part.split("=", 1)[-1])
            elif part.startswith("crit="):
                crit_time = float(part.split("=", 1)[-1])
        remote_time = float(output.rsplit(" ", 1)[-1])
        local_time = time.time()
        offset = local_time - remote_time
        remote_ftime = time.strftime("%c", time.localtime(remote_time))
        if abs(offset)>=crit_time:
            status = "ERROR"
            exit_code = 2
        elif abs(offset)>=warn_time:
            status = "WARNING"
            exit_code = 1
        else:
            status = "OK"
            exit_code = 0
        print(
            f"TimeSync {status} - offset={offset:5.3}s, {remote_ftime}|"
            f"offset={offset}s"
        )
        sys.exit(exit_code)
    except Exception as err:
        print(f"TimeSync ERROR - {err}, \"{output}\"")
else:
    # Just display current time
    ftime = time.strftime("%c")
    ts = time.time()
    print(f"TimeSync OK - {ftime}, warn={warn_time}, crit={crit_time}, {ts}")
