#!/bin/bash
# -*- sh -*-

: << =cut

=head1 NAME

ssl_ - Plugin to monitor certificate expiration

=head1 CONFIGURATION

This plugin does not normally require configuration.

To set warning and critical levels do like this:

  [ssl_*]
      env.warning 30:

=head1 AUTHOR

Pactrick Domack

Copyright (C) 2013 Patrick Domack <patrickdk@patrickdk.com>

=head1 LICENSE

=cut

. $MUNIN_LIBDIR/plugins/plugin.sh

SITE=${0##*ssl_}

case $1 in
    config)

        echo "graph_title $SITE SSL Certificate Expire"
        echo 'graph_args --base 1000'
        echo 'graph_vlabel days left'
        echo 'graph_category ssl'
        echo "graph_info This graph shows the days left for the certificate being served by $SITE"
        echo 'expire.label days'
        print_warning expire
        print_critical expire

        exit 0
        ;;
esac

cert=$(echo "" | openssl s_client -CApath /etc/ssl/certs -servername "${SITE}" -connect "${SITE}:443" 2>/dev/null);

if [[ "${cert}" = *"-----BEGIN CERTIFICATE-----"* ]]; then
  echo "${cert}" | openssl x509 -noout -enddate | awk -F= 'BEGIN { split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month, " "); for (i=1; i<=12; i++) mdigit[month[i]] = i; } /notAfter/ { split($0,a,"="); split(a[2],b," "); split(b[3],time,":"); datetime=b[4] " " mdigit[b[1]] " " b[2] " " time[1] " " time[2] " " time[3]; days=(mktime(datetime)-systime())/86400; print "expire.value " days; }'
fi
