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

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

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

DEFAULT_CRIT = 50  # #updates
DEFAULT_WARN = 2  # #updates


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(
        '-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(
        '--timeout',
        help=argparse.SUPPRESS,
        dest='TIMEOUT',
        type=int,
        default=300,
    )

    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)

    # fetch data
    cmd = """
    $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;
    }
    """
    result = lib.powershell.run_ps(cmd)
    if result['retc']:
        lib.base.cu(result['stderr'])
    result = result['stdout'].strip()

    count = sum(1 for line in result.splitlines())
    perfdata = lib.base.get_perfdata(
        'pending_updates',
        count,
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
    )

    if count:
        state = lib.base.get_state(count, args.WARN, args.CRIT)
        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,
        )

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


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