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

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

DESCRIPTION = """Checks the current disk usage of all systemd journal files (archived and active
combined). Alerts when journal disk usage exceeds the configured thresholds.
Requires root or sudo."""

DEFAULT_WARN = 6  # GiB; journald: "capped to 4G" per default
SYSTEMD_DEFAULT_MAX_USE = '4G'
SYSTEMD_DEFAULT_KEEP_FREE = '1M'


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

    parser.add_argument(
        '-w',
        '--warning',
        help='WARN threshold in GiB. Default: >= %(default)s',
        dest='WARN',
        type=int,
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def extract_config(output):
    """
    Extracts the last occurrences of SystemMaxUse and SystemKeepFree.
    Returns a tuple: (SystemMaxUse_value, SystemKeepFree_value).
    """
    max_use = None
    keep_free = None
    for line in reversed(output.splitlines()):
        if max_use is None and line.startswith('SystemMaxUse='):
            max_use = line.split('=', 1)[1].strip()
        if keep_free is None and line.startswith('SystemKeepFree='):
            keep_free = line.split('=', 1)[1].strip()
        if max_use is not None and keep_free is not None:
            break
    if max_use is None:
        max_use = SYSTEMD_DEFAULT_MAX_USE
    if keep_free is None:
        keep_free = SYSTEMD_DEFAULT_KEEP_FREE
    return max_use, keep_free


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 = 'journalctl --disk-usage'
        stdout, stderr, _ = lib.base.coe(lib.shell.shell_exec(cmd))
        if stderr:
            lib.base.cu(stderr)

        # get journald's thresholds
        cmd = 'systemd-analyze cat-config systemd/journald.conf'
        config, stderr, _ = lib.base.coe(lib.shell.shell_exec(cmd))
        if stderr:
            lib.base.cu(stderr)
        max_use, keep_free = extract_config(config)
    else:
        # do not call the command, put in test data
        stdout, stderr, _ = lib.lftest.test(args.TEST)
        max_use, keep_free = SYSTEMD_DEFAULT_MAX_USE, SYSTEMD_DEFAULT_KEEP_FREE

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

    # possible values of stdout according to systemd journalctl.c source code history:
    #   Archived and active journals take up %s on disk.\n
    #   Archived and active journals take up %s in the file system.\n
    #   Journals take up %s on disk.\n
    value = lib.txt.extract_str(
        stdout, ' take up ', ' ', include_fromto=False, be_tolerant=False
    )
    value = lib.human.human2bytes(value)

    # build the message
    state = lib.base.get_state(value, args.WARN * 1024 * 1024 * 1024, None)
    msg += (
        f'{lib.human.bytes2human(value)} used{lib.base.state2str(state, prefix=" ")} '
        '(sum of all archived and active journal files; '
        f'SystemMaxUse={max_use} SystemKeepFree={keep_free})'
    )
    if state != STATE_OK:
        msg += (
            '. Configure `SystemMaxUse` and `SystemKeepFree` in '
            '`/etc/systemd/journald.conf/`, '
            'or remove the oldest archived journal files by using '
            '`journalctl --vacuum-size=`, `--vacuum-time=` and/or `--vacuum-files=`.'
        )
    perfdata += lib.base.get_perfdata(
        'journald-usage',
        value,
        uom='B',
        warn=args.WARN * 1024 * 1024 * 1024,
        crit=None,
        _min=0,
        _max=None,
    )

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


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