#!/bin/sh
# reinhard@finalmedia.de
# use in /usr/lib/check_mk_agent/local/

export servicename="Zertifikatlaufzeit"
export warndays=14
export host="HIER_DEINE_HOST_IP_FUER_CHECK"
export port="443"
export certpath="HIER_DER_ACME_USER/.acme.sh/"
export certsuffix=".cer"

(find "${certpath}" -name "*${certsuffix}" -type f \
-not -name "fullchain.cer" -not -name "ca.cer" | \
while read certfile
do
domain="$(openssl x509 -noout -subject -in "${certfile}" | cut -d= -f3 | tr -dc "0-9a-z._-")"
enddatetime="$(echo | timeout 5 openssl s_client \
-connect "${host}:${port}" \
-showcerts -servername "${domain}" 2>/dev/null | \
openssl x509 -dates -noout 2>&1 | grep "^notAfter=" | \
cut -d= -f2- | tr -dc "0-9a-zA-Z.: ")"
test -z "${enddatetime}" && echo "${domain}(ERR) " && continue
stamp="$(date +'%s' -d "$enddatetime" | tr -dc "0-9")"
stampnow="$(date +'%s')"
stampdiff=$((stamp-stampnow))
days=$((stampdiff/84600))
status=0
test $days -gt $warndays && echo "$domain(${days})" || echo "$domain(!${days})"
done
) | sort -t"(" -k2 -n | tr "\n" " " | \
awk '{print "count=" NF " " $0}' | \
sed '
s/^/0 %SERVICENAME% status=0|/g;
s/^\(0\)\(.*ERR\)/2 \2*/g;
s/^\(0\)\(.*!\)/1 \2*/g;
s/\(.\)\(.*\)\(status=.|\)\(.*\)/\1\2status=\1|\4/g;
' | tr -s " " | tr -d "*" | sed "s/%SERVICENAME%/${servicename}/g"
