#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details."""

import argparse
import sys

import lib.args
import lib.base
import lib.human
import lib.lftest
import lib.shell
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026041001'

DESCRIPTION = """Checks the clock offset of ntpd in milliseconds compared to the configured NTP
servers. Alerts when the offset exceeds the configured thresholds."""

DEFAULT_CRIT = 86400000  # 24h in ms offset
DEFAULT_STRATUM = 6
DEFAULT_WARN = 800  # ms offset


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '-c',
        '--critical',
        help='CRIT threshold for the NTP time offset, in milliseconds. '
        'Default: %(default)sms',
        dest='CRIT',
        type=int,
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--stratum',
        help=lib.args.help('--stratum') + ' Default: %(default)s',
        dest='STRATUM',
        type=int,
        default=DEFAULT_STRATUM,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '-w',
        '--warning',
        help='WARN threshold for the NTP time offset, in milliseconds. '
        'Default: %(default)sms',
        dest='WARN',
        type=int,
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)


    # fetch data
    if args.TEST is None:
        cmd = 'ntpq -p'
        stdout, stderr, _ = lib.base.coe(lib.shell.shell_exec(cmd))
    else:
        # do not call the command, put in test data
        stdout, stderr, _ = lib.lftest.test(args.TEST)
    if stderr:
        lib.base.cu(stderr)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''

    delay = '0'
    jitter = '0'
    offset = None
    peer = ''
    peer_used = False
    stratum = 0

    # analyze data
    for line in stdout.splitlines():
        line = line.strip()
        if line.startswith('*'):
            peer_used = True
            try:
                # line of peer in the form
                # [tally]remote refid st t when pool reach delay offset jitter
                split_line = line[1:].split()  # remove '*' and split

                # get numeric values via negative index as there might be
                # multiple whitespaces in remote
                peer = split_line[0]
                stratum = int(split_line[-8])
                delay = split_line[-3]
                offset = float(split_line[-2])
                jitter = split_line[-1]
            except Exception:
                pass

    if offset is None or not peer_used:
        lib.base.oao('No NTP server used.', STATE_WARN)
    elif peer == '':
        lib.base.oao('No NTP server found.', STATE_WARN)
    elif peer == 'LOCAL':
        lib.base.oao('Only LOCAL clock is used.', STATE_WARN)

    # build the message
    offset_state = lib.base.get_state(abs(offset), args.WARN, args.CRIT)
    state = lib.base.get_worst(state, offset_state)
    msg += (
        f'NTP offset is {offset}ms{lib.base.state2str(offset_state, prefix=" ")}, '
        f'Stratum is {stratum}'
    )
    if stratum >= args.STRATUM:
        stratum_state = STATE_WARN
        state = lib.base.get_worst(state, stratum_state)
        msg += f' (is >= {args.STRATUM} {lib.base.state2str(stratum_state)})'

    perfdata += lib.base.get_perfdata(
        'delay',
        delay,
        uom='ms',
        warn=None,
        crit=None,
        _min=None,
        _max=None,
    )
    perfdata += lib.base.get_perfdata(
        'jitter',
        jitter,
        uom='ms',
        warn=None,
        crit=None,
        _min=None,
        _max=None,
    )
    perfdata += lib.base.get_perfdata(
        'offset',
        offset,
        uom='ms',
        warn=args.WARN,
        crit=args.CRIT,
        _min=None,
        _max=None,
    )
    perfdata += lib.base.get_perfdata(
        'stratum',
        stratum,
        uom=None,
        warn=args.STRATUM,
        crit=None,
        _min=0,
        _max=16,
    )

    # over and out
    lib.base.oao(msg + '\n\n' + stdout, state, perfdata)


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
