#!/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.

# Example output from agent:
# <<<windows_tasks:sep(58)>>>
# TaskName             : \WebShopPictureUpload
# Last Run Time        : 17.10.2013 23:00:00
# Next Run Time        : 18.10.2013 23:00:00
# Last Result          : 0
# Scheduled Task State : Enabled
#
# TaskName             : \OfficeSoftwareProtectionPlatform\SvcRestartTask
# Last Run Time        : N/A
# Next Run Time        : Disabled
# Last Result          : 1
# Scheduled Task State : Disabled

# A list of all task state can be found here:
# http://msdn.microsoft.com/en-us/library/aa383604%28VS.85%29.aspx


# From here: http://systemcentercore.com/?GetElement=Custom.TaskScheduler2.Task.LastResult.Monitor&Type=UnitMonitor&ManagementPack=Custom.Windows.TaskScheduler.Windows2008.Monitoring&Version=1.1.1.0

# Windows Scheduled Task Last Result Monitor.
#The monitor checks the last result code (exit code) of a scheduled task.
#Anything other than the following values is considered a warning condition for an enabled scheduled task.
#- '0'
#- '1' (for tasks containing a popup action)
#- '267009': currently running
#- '267014': was terminated by user
#- '267045': queued
#- '-2147216609': instance of this task already running -> being taken care of by the separate monitor
#- '-2147750687': task already running -> being taken care of by the separate monitor

def windows_tasks_convert(info):
    data = {}
    last_task = False
    for line in info:
        name = line[0].strip()
        value = ":".join(line[1:]).strip()
        if last_task and name != "TaskName":
            data[last_task][name] = value

        if name == 'TaskName':
            last_task = value
            data[last_task] = {}
    return data

def inventory_windows_tasks(info):
    info = windows_tasks_convert(info)
    return [ (n, None) for n, v in info.items() if v.get('Scheduled Task State') == "Enabled"]

def check_windows_tasks(item, _no_params, info):
    info = windows_tasks_convert(info)
    for name, values in info.items():
        if name == item:
            last_result = saveint(values['Last Result'])
            state = 0
            label = ""
            msg = []
            if last_result not in [ 0, 1, 267009, 267014, 267045, -2147216609, -2147750687 ]:
                state = 2
                label = "(!!)"
            msg.append("Service in state: %s%s" % ( last_result, label ) )
            if last_result == 267009:
                msg[-1] += " (currently running)"
            elif last_result == 267014:
                msg[-1] += " (terminated by user)"
            elif last_result == 267045:
                msg[-1] += " (queued)"
            elif last_result == -2147216609:
                msg[-1] += " (an instance of the task already running)"
            elif last_result == -2147750687:
                msg[-1] += " (task already running)"

            if values['Scheduled Task State'] != 'Enabled':
                msg.append("Task not Enabled(!!)")
                state = 2

            if "Last Run Time" in values:
                msg.append("last run time: %s" % values["Last Run Time"])

            if "Next Run Time" in values:
                msg.append("next run time: %s" % values["Next Run Time"])

            return state, ", ".join(msg)

    return 3, "Task not found on server"

check_info["windows_tasks"] = {
    "check_function"        : check_windows_tasks,
    "inventory_function"    : inventory_windows_tasks,
    "service_description"   : "Task %s",
    "has_perfdata"          : False,
}

