#!/bin/sh
# -*- 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

# shellcheck disable=SC1090
. "$MUNIN_LIBDIR/plugins/plugin.sh"

ARGS=${0##*ssl_}
if echo "$ARGS" | grep -q "_"; then
    SITE=$(echo "$ARGS" | cut -f 1 -d "_")
    PORT=$(echo "$ARGS" | cut -f 2 -d "_")
else
    SITE=$ARGS
    PORT=443
fi


# Read data including a certificate from stdin and output the (fractional) number of days left
# until the expiry of this certificate. The output is empty if parsing failed.
parse_valid_days_from_certificate() {
    local input_data
    local valid_until_string
    local valid_until_epoch
    local now_epoch
    local input_data
    input_data=$(cat)
    if echo "$input_data" | grep -q -- "-----BEGIN CERTIFICATE-----"; then
        valid_until_string=$(echo "$input_data" | openssl x509 -noout -enddate \
            | grep "^notAfter=" | cut -f 2 -d "=")
        if [ -n "$valid_until_string" ]; then
            valid_until_epoch=$(date --date="$valid_until_string" +%s)
            if [ -n "$valid_until_epoch" ]; then
                now_epoch=$(date +%s)
                # calculate the number of days left
                echo "$valid_until_epoch" "$now_epoch" | awk '{ print(($1 - $2) / (24 * 3600)); }'
            fi
        fi
    fi
}


case $1 in
    config)

        echo "graph_title $SITE SSL Certificate Expire"
        echo 'graph_args --base 1000'
        echo 'graph_vlabel days left'
        echo 'graph_category security'
        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}:${PORT}" 2>/dev/null);

days_left=$(echo "$cert" | parse_valid_days_from_certificate)
[ -n "$days_left" ] || days_left="U"

printf "expire.value %s\n" "$days_left"
