#!/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
# <<<jar_signature>>>
# [[[bluecove-1.2.3-signed.jar]]]
# sm       308 Fri May 11 01:42:04 CEST 2007 javax/microedition/io/StreamConnectionNotifier.class
#
#       X.509, CN=MicroEmulator Team
#             [certificate expired on 2/10/12 6:19 PM]
#
#
#               s = signature was verified
#                 m = entry is listed in manifest
#                   k = at least one certificate was found in keystore
#                     i = at least one certificate was found in identity scope
#
#                     jar verified.
#
#                     Warning:
#                     This jar contains entries whose signer certificate has expired.


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, _no_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]
    # [certificate expired on 2/10/12 6:19 PM]
    if "will expire on " in cert_valid:
        expiry_date_text = cert_valid.split("will expire on ", 1)[1][:-1]
    elif "expired on" in cert_valid:
        expiry_date_text = cert_valid.split("expired on ", 1)[1][:-1]
    else:
        expiry_date_text = cert_valid.split("to ", 1)[1][:-1]
    expiry_date = time.mktime(time.strptime(expiry_date_text, '%m/%d/%y %I:%M %p'))
    expired_since = time.time() - expiry_date

    warn, crit = 60 * 86400, 30 * 86400

    state = 0
    if expired_since >= 0:
        state = 2
        status_text = "Certificate expired on %s (%s ago) " % (expiry_date_text, get_age_human_readable(expired_since))
    else:
        status_text = "Certificate will expire on %s (in %s)" % (expiry_date_text, get_age_human_readable(-expired_since))
        if -expired_since <= crit:
            state = 2
            status_txt = "(less than %s)" % (get_age_human_readable(crit))
        elif -expired_since <= warn:
            state = 1
            status_txt = "(less than %s)" % (get_age_human_readable(warn))

    return state, status_text


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