#!/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__ = '2026040801'

DESCRIPTION = """Checks system clock and RTC settings via timedatectl, including whether network time
synchronization is active and whether the system clock is synchronized. Alerts on
misconfigured time settings."""


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(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    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:
        # Do NOT use `timedatectl show` if you want to be compatible to older
        # systemd versions, as this is only available since 2018-05 (and therefore not on RHEL 7).
        # Use `timedatectl status` instead.
        cmd = 'timedatectl status'
        stdout, stderr, _retc = lib.base.coe(lib.shell.shell_exec(cmd))
        if stderr:
            lib.base.oao(f'{stderr}', STATE_WARN)
    else:
        # do not call the command, put in test data
        stdout, stderr, _retc = lib.lftest.test(args.TEST)

    # init some vars
    msg = ''
    state = STATE_OK

    # analyze data and build the message
    # i->ntp_synced
    msg += lib.txt.extract_str(
        stdout, 'NTP synchronized: ', '\n', include_fromto=True
    ).replace('\n', ', ')

    # build the message
    msg += lib.txt.extract_str(
        stdout, 'System clock synchronized: ', '\n', include_fromto=True
    ).replace('\n', ', ')

    # yes_no(i->ntp), i->ntp_capable
    msg += lib.txt.extract_str(
        stdout, 'NTP enabled: ', '\n', include_fromto=True
    ).replace('\n', ', ')
    msg += lib.txt.extract_str(
        stdout, 'systemd-timesyncd.service active: ', '\n', include_fromto=True
    ).replace('\n', ', ')
    msg += lib.txt.extract_str(
        stdout, 'NTP service: ', '\n', include_fromto=True
    ).replace('\n', ', ')

    msg = msg[:-2]

    if 'RTC in local TZ: yes' in stdout:
        state = STATE_WARN
        msg += (
            '. The system is configured to read the RTC time in the local time zone. '
            'This mode cannot be fully supported. It will create various problems '
            'with time zone changes and daylight saving time adjustments. The RTC '
            'time is never updated, it relies on external facilities to maintain it. '
            'If at all possible, use RTC in UTC by calling '
            f'`timedatectl set-local-rtc 0`{lib.base.state2str(state, prefix=" ")}.'
        )
    else:
        msg += ', RTC in local TZ: no'

    # over and out
    lib.base.oao(msg, state, always_ok=args.ALWAYS_OK)


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