#!/bin/sh
# check_dehydrated v1.0.1  (c) 13.2.2020 by Andreas Ley  (u) 1.8.2020
# Check dehydrated keys on all cluster nodes

root="/var/www"
mailfrom="apache@scc.kit.edu"
mailto="webmaster@kit.edu"
#mailto="${mailfrom}"

usage()
{
	echo "Usage: `basename $0` [-v] [FQDN [...]]" >&2
	echo "-v  verbose mode" >&2
	exit 1
}

set -- `getopt hxv $*` || usage

trace=false
verbose=false
while :; do
	case $1 in
		-h)	sed '1d;s/^# *//;/^$/q' $0; usage;;
		-x)	set -x; trace=true; shift;;
		-v)	verbose=true; shift;;
		--)	shift; break;;
	esac
done

cd "${root}" || exit 1
test $# -eq 0 && set *.*.*

tmpname="`/bin/mktemp`"
trap "rm -f \"${tmpname}\"" 0 1 2 3 15

for fqdn; do
	cert=$(readlink "${root}/${fqdn}/conf/ssl/dehydrated/cert.pem")
	if test -n "$cert"; then
		hosts=$(clcmd -f -s all "sh -c 'test \$(readlink \"${root}/${fqdn}/conf/ssl/dehydrated/cert.pem\") = \"$cert\" || hostname'")
		if test -n "${hosts}"; then
			{
			echo "From: ${mailfrom}"
			echo "To: ${mailto}"
			echo "Cc: ${mailfrom}"
			echo "Subject: ${fqdn}: Inconsistent dehydrated certificates"
			echo
			echo "Usually, ${root}/${fqdn}/conf/ssl/dehydrated/cert.pem is a symlink to the latest LE certificate (the number is a unix timestamp, i.e. seconds since the epoch). This symlink and the file it points to should be distributed to all cluster nodes upon renewal. Well, something bad must have happened, like a node being unavailable at the time of distribution or systemd killing us at the end of the logrotate run due to DNS server updates not yet being realtime :-( It should be safe to run \"dist ${root}/${fqdn}/conf/ssl/dehydrated/\" on one of the nodes with the highest timestamp, but use your common sense!"
			echo
			echo "The dehydrated certificates for ${fqdn} for the following hosts differ from $(hostname):"
			echo ${hosts}
			echo
			echo "Here is a view on all the cluster nodes:"
			clcmd -vf "ls -l \"${root}/${fqdn}/conf/ssl/dehydrated/cert.pem\"" 2>&1
			} | /usr/lib/sendmail -i -t
		fi
	fi
done

exit 0
