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

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

DESCRIPTION = """Checks how long ago the last APT package manager activity occurred (install, update, or remove). Alerts if no package management activity has happened within the configured thresholds (default: WARN after 90 days, CRIT after 365 days). 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 time since last package manager activity, in days. '
        'Default: %(default)s',
        type=int,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '-w',
        '--warning',
        default=DEFAULT_WARN,
        dest='WARN',
        help='WARN threshold for time since last package manager 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
    if args.TEST is None:
        # execute the shell command and return its result and exit code
        stdout, stderr, _ = lib.base.coe(
            lib.shell.shell_exec(
                "dpkg-query --show --showformat='${db-fsys:Last-Modified} ${Package}\n'"
            )
        )
        if stderr:
            lib.base.cu(stderr)
    else:
        # do not call the command, put in test data
        stdout, _, _ = lib.lftest.test(args.TEST)

    # stdout: 1680072089 adduser\n1680072121 apparmor\n1680072091 apt\n
    try:
        last_activity = lib.txt.mltext2array(stdout, skip_header=False, sort_key=0)
        last_activity = int(last_activity[-1][0])
    except ValueError:
        lib.base.oao(
            'Missing "Last-Modified" timestamp for one or more '
            'packages. Check the output of `dpkg-query --show '
            "--showformat='${db-fsys:Last-Modified} "
            "${Package}\\n'`. It is likely that some files have "
            'been deleted. The best thing to do is to reinstall '
            'these packages.',
            STATE_WARN,
        )
    except Exception:
        lib.base.cu('Unable to get dpkg-query 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()
