#!/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.lftest
import lib.shell
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks the state of systemd-timesyncd, including synchronization status, server
reachability, and stratum level. Alerts if time synchronization is inactive or if
the stratum exceeds the configured limit."""

DEFAULT_STRATUM = 6


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(
        '--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,
    )

    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 = 'timedatectl show-timesync --all'
        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 = ''

    peer_used = False

    # analyze data
    for line in stdout.splitlines():
        line = line.strip()
        if line.startswith('ServerAddress='):
            peer_used = line.split('=')[-1] != '(null)'
            continue
        if line.startswith('NTPMessage='):
            for ntpmsg in (
                line.replace('NTPMessage={ ', '').replace(' }', '').split(', ')
            ):
                if ntpmsg.startswith('Stratum'):
                    stratum = int(ntpmsg.split('=')[-1])
                    break

    if not peer_used:
        lib.base.oao('No NTP server used.', STATE_WARN)

    # build the message
    msg += 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(
        '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()
