#!/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  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.args  # pylint: disable=C0413
import lib.base  # pylint: disable=C0413
import lib.shell  # pylint: disable=C0413
import lib.lftest  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN,  # pylint: disable=C0413
                          STATE_WARN)

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

DESCRIPTION = """Checks current settings of the system clock and RTC, including whether network
                 time synchronization is active."""


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

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

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--test',
        help='For unit tests. Needs "path-to-stdout-file,path-to-stderr-file,expected-retc".',
        dest='TEST',
        type=lib.args.csv,
    )

    return parser.parse_args()


def main():
    """The main function. Hier spielt die Musik.
    """

    # parse the command line, exit with UNKNOWN if it fails
    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)) # pylint: disable=W0612
        if stderr:
            lib.base.oao('{}'.format(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', ', ')
    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 ' \
               '`timedatectl set-local-rtc 0`{}.'.format(
            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:   # pylint: disable=W0703
        lib.base.cu()
