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

import datetime, time

def inventory_jar_signature(info):
    inventory = []
    for line in info:
        if line[0].startswith("[[["):
            f = line[0][3:-3]
            inventory.append((f, {}))
    return inventory

def check_jar_signature(item, params, info):
    in_block = False
    details = []
    in_cert = False
    cert = []
    for line in info:
        line = (" ".join(line)).strip()
        if line == "[[[%s]]]" % item:
            in_block = True
        elif in_block and line.startswith("[[["):
            break
        elif in_block and line.startswith("X.509"):
            in_cert = True
            cert = [line]
        elif in_block and in_cert and line.startswith("[") and not line.startswith("[entry was signed on"):
            in_cert = False
            cert.append(line)
            details.append(cert)

    if not details:
        return (2, "No certificate found")

    cert_dn, cert_valid = details[0]

    # [certificate is valid from 3/26/12 11:26 AM to 3/26/17 11:36 AM]
    # [certificate will expire on 7/4/13 4:13 PM]
    if "will expire on " in cert_valid:
        to = cert_valid.split("will expire on ", 1)[1][:-1]
    else:
        to = cert_valid.split("to ", 1)[1][:-1]
    to_dt = datetime.datetime(*time.strptime(to, '%m/%d/%y %I:%M %p')[:6])

    warn, crit = 60, 30

    state = 0
    status_txt = ""
    if to_dt < datetime.datetime.now() + datetime.timedelta(days = crit):
        state = 2
        status_txt = " (less than %d days)" % crit
    elif to_dt < datetime.datetime.now() + datetime.timedelta(days = warn):
        state = 1
        status_txt = " (less than %d days)" % warn

    return state, "Certificate expires on %s%s (%s)" % (to, status_txt, cert_dn)

check_info['jar_signature'] = {
    "service_description"     : "Jar-Signature %s",
    "check_function"          : check_jar_signature,
    "inventory_function"      : inventory_jar_signature,
}
