#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# <<<windows_updates>>>
# 0 2 5
# Windows XP Service Pack 3 (KB936929); Windows-Tool zum Entfernen sch�dlicher Software - M�rz 2011 (KB890830)
# Update f�r WMDRM-f�hige Medienplayer (KB891122); Windows Media Player 11; Windows Search 4.0 f�r Windows XP (KB940157); Microsoft Base Smartcard-Kryptografiedienstanbieter-Paket: x86 (KB909520); Update f�r die Microsoft .NET Framework 3.5 Service Pack 1- und .NET Framework 3.5-Produktfamilie (KB951847) x86

# First row:  Reboot_required, num_important, num_optional
# Second row: List of all important updates (optional)
# Third row:  List of all optional updates (optional)
# Last row:  Date and time of forced update (optional)

windows_updates_default_params = (0, 0, 0, 0, 604800, 172800, True)

def inventory_windows_updates(info):
    if info and len(info[0]) == 3:
        return [(None, "windows_updates_default_params")]

def check_windows_updates(_no_item, params, info):
    if info and len(info[0]) == 3:
        status = 0
        # Workarround to return errors from the plugin
        if info[0][0] == 'x':
            return 2, ' '.join(info[1])
        reboot_required, num_imp, num_opt = map(saveint, info[0])
        imp_warn, imp_crit, opt_warn, opt_crit = params[0:4]
        if len(params) == 7:
            force_warn, force_crit, verbose = params[4:7]
        else:
            force_warn = 604800
            force_crit = 172800
            verbose = True
        important = ''
        optional = ''

        last = 1
        if num_imp != 0:
            important = ' '.join(info[1])
            last += 1
        if num_opt != 0 and num_imp != 0:
            last += 1
            optional = ' '.join(info[2])
        elif num_opt != 0:
            last += 1
            optional = ' '.join(info[1])

        # the last element may be the forced_reboot time
        forced_reboot = ""
        if len(info) - 1 == last and len(info[last]) == 2:
            forced_reboot = info[last]

        txt = []
        perfdata = []
        for label, updates, cur, warn, crit in [ ('important', important, num_imp, imp_warn, imp_crit),
                                                 ('optional',  optional,  num_opt, opt_warn, opt_crit) ]:
            this_txt = '%d %s updates' % (cur, label)
            if crit and cur >= crit:
                this_txt += ' >=%d (!!)' % crit
                if status < 2:
                    status = 2
            elif warn and cur >= warn:
                this_txt += ' >=%d (!)' % warn
                if status < 1:
                    status = 1
            if label == 'important' and cur > 0 and verbose:
                this_txt += ', (%s) --- ' % updates
            txt.append(this_txt)
            perfdata.append((label, cur, warn, crit))

        if reboot_required == 1:
            if status < 1:
                status = 1
            txt.append('Reboot required to finish updates(!)')

        if forced_reboot != "":
            parsed = time.strptime(" ".join(forced_reboot), "%Y-%m-%d %H:%M:%S")
            now = int(time.time())
            delta = time.mktime(parsed) - now

            # check if force_date is in the future
            if delta >= 0:
                sym = ""
                if force_crit and delta <= force_crit:
                    sym = "(!!)"
                    status = 2
                elif force_warn and delta <= force_warn:
                    sym = "(!)"
                    status = max(status, 1)

                boot_txt = 'Reboot enforced in %s to finish updates%s' % (get_age_human_readable(delta), sym)
                txt.append(boot_txt)

        return (status, ', '.join(txt), perfdata)

    return (3, 'No windows update information provided')


check_info["windows_updates"] = {
    'check_function':          check_windows_updates,
    'inventory_function':      inventory_windows_updates,
    'service_description':     'System Updates',
    'group':                   'windows_updates',
    'has_perfdata':            True,
}
