#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- 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.powershell
import lib.txt
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks the number of pending Windows updates. Alerts when the update count exceeds the
configured thresholds."""

DEFAULT_CRIT = 50  # #updates
DEFAULT_TIMEOUT = (
    300  # the Windows Update search; the command timeout of the basket is 600
)
DEFAULT_WARN = 2  # #updates


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__),
        formatter_class=lib.args.HelpFormatter,
    )

    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(
        '-c',
        '--critical',
        default=DEFAULT_CRIT,
        dest='CRIT',
        help='Threshold for the number of pending updates. Default: %(default)s',
        type=lib.args.int_or_none,
    )

    parser.add_argument(
        '--no-perfdata',
        help=lib.args.help('--no-perfdata'),
        dest='NO_PERFDATA',
        action='store_true',
        default=False,
    )

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

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-w',
        '--warning',
        default=DEFAULT_WARN,
        dest='WARN',
        help='Threshold for the number of pending updates. Default: %(default)s',
        type=lib.args.int_or_none,
    )

    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)

    if args.TEST is None and not lib.base.WINDOWS:
        lib.base.cu('This check runs on Windows only.')

    # fetch data
    # The HRESULT tells the causes apart in every display language, the message of
    # the exception is translated.
    cmd = """
    try {
        $WindowsUpdates = New-Object -ComObject 'Microsoft.Update.Session';
        $SearchIndex = $WindowsUpdates.CreateUpdateSearcher();
        $Pending = $SearchIndex.Search('IsInstalled=0');
        foreach ($update in $Pending.Updates) {
            $name = "{0} [{1}]" -f $update.Title, $update.LastDeploymentChangeTime;
            Write-Output $name;
        }
    } catch {
        [Console]::Error.WriteLine(
            ('0x{0:X8} {1}' -f $_.Exception.HResult, $_.Exception.Message)
        );
        exit 1;
    }
    """
    if args.TEST is None:
        result = lib.powershell.run_ps(cmd, timeout=args.TIMEOUT)
        if result['retc'] and result['stderr'].startswith('Timeout after'):
            lib.base.oao(
                f'Timeout after {args.TIMEOUT}s while searching for Windows updates.',
                STATE_WARN,
                always_ok=args.ALWAYS_OK,
            )
        if result['retc']:
            # E_ACCESSDENIED from the search, measured with the Icinga 2 agent running
            # as NetworkService (its MSI default) on Windows Server 2025
            if result['stderr'].startswith('0x80070005'):
                lib.base.cu(
                    'Access denied while searching for Windows updates. The account the'
                    ' check runs as may not search for them; NetworkService, which the'
                    ' Icinga 2 agent uses by default, may not. Run the check through a'
                    ' JEA endpoint, see'
                    ' https://linuxfabrik.github.io/monitoring-plugins/plugins-windows/'
                )
            # ERROR_SERVICE_DISABLED, measured on Windows Server 2022 with wuauserv
            # disabled. A host that cannot search for updates does not install them
            # either, which is worth a warning rather than an UNKNOWN.
            if result['stderr'].startswith('0x80070422'):
                lib.base.oao(
                    'The Windows Update service (wuauserv) is disabled, so this host'
                    ' neither searches for nor installs updates.',
                    STATE_WARN,
                    always_ok=args.ALWAYS_OK,
                )
            lib.base.cu(result['stderr'])
        result = result['stdout'].strip()
    else:
        # do not call the command, put in test data
        stdout, _, _ = lib.lftest.test(args.TEST)
        result = stdout.strip()

    # init some vars
    count = sum(1 for line in result.splitlines())

    # analyze data
    # no pending update is always OK, whatever the thresholds say
    state = lib.base.get_state(count, args.WARN, args.CRIT) if count else STATE_OK

    # build the message
    perfdata = lib.base.get_perfdata(
        'pending_updates',
        count,
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
    )
    if count:
        bullet_list = result.replace('\n', '\n* ')
        lib.base.oao(
            (
                f'There {lib.txt.pluralize("", count, "is,are")} {count} pending '
                f'{lib.txt.pluralize("update", count)}:\n\n'
                f'* {bullet_list}'
            ),
            state,
            perfdata,
            always_ok=args.ALWAYS_OK,
            no_perfdata=args.NO_PERFDATA,
        )

    # over and out
    lib.base.oao(
        'There are no pending updates.',
        STATE_OK,
        perfdata,
        always_ok=args.ALWAYS_OK,
        no_perfdata=args.NO_PERFDATA,
    )


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