#!/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.base
import lib.human
import lib.shell
import lib.time
import lib.txt
from lib.globals import STATE_UNKNOWN

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

DESCRIPTION = """Checks how long ago the last RPM package manager activity occurred (install, update, or remove via yum/dnf). Alerts if no package management activity has happened within the configured thresholds. Useful for detecting servers that have not been patched in a long time."""

DEFAULT_WARN = 90  # days
DEFAULT_CRIT = 365  # days


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',
        default=DEFAULT_CRIT,
        dest='CRIT',
        help='CRIT threshold for the time since the last RPM activity, in days. '
        'Default: %(default)s',
        type=int,
    )

    parser.add_argument(
        '-w',
        '--warning',
        default=DEFAULT_WARN,
        dest='WARN',
        help='WARN threshold for the time since the last RPM activity, in days. '
        'Default: %(default)s',
        type=int,
    )

    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
    stdout, stderr, _ = lib.base.coe(
        lib.shell.shell_exec(
            'rpm --query --all --queryformat "%{INSTALLTIME} %{NAME}\n"'
        )
    )
    if stderr:
        lib.base.cu(stderr)

    # stdout: '1662130946 unbound-libs\n1662130898 NetworkManager-libnm\n'
    try:
        last_activity = lib.txt.mltext2array(stdout, skip_header=False, sort_key=0)
        last_activity = int(last_activity[-1][0])
    except Exception:
        lib.base.cu('Unable to get rpm info, maybe an update never happened.')

    # calculating the final check state
    delta = lib.time.now() - last_activity
    state = lib.base.get_state(
        delta, args.WARN * 24 * 60 * 60, args.CRIT * 24 * 60 * 60
    )

    # over and out
    lib.base.oao(
        (
            f'Last package manager activity is'
            f' {lib.human.seconds2human(delta)} ago'
            f'{lib.base.state2str(state, prefix=" ")}'
            f' (thresholds {args.WARN}D/{args.CRIT}D).'
        ),
        state,
    )


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