#!/bin/bash

. /etc/certwatch/config.sh

PASS=1

check_domain() {
	DOMAIN="$1"
	shift;
	DAYS=14
	CRT=$(echo "" | openssl s_client $@ 2>/dev/null);
	if [[ $? != 0 ]]; then
		PASS=0
		send_notification "Check failed for $DOMAIN" "$CRT";
		return;
	fi

	if (echo "$CRT" | openssl x509 -noout -checkend $(($DAYS*3600*24)) >/dev/null 2>&1); then
		return;
	fi
	MSG=$(echo "$CRT" | openssl x509 -noout -text|egrep 'CN|DNS|Not After' 2>/dev/null)
	PASS=0
	send_notification "Certificate expiry: $DOMAIN" "$MSG"
}

check_https() {
	check_domain "$1 HTTPS" -servername $1 -connect $1:443
}

check_xmpp() {
	# need OpenSSL 1.1 for -xmpphost :(
	check_domain "$1 XMPP" -connect $1:5222 -starttls xmpp
}

check_xmpps2s() {
	# need OpenSSL 1.1 for -xmpphost :(
	check_domain "$1 XMPP" -connect $1:5269 -starttls xmpp
}

check_smtp() {
	check_domain "$1 SMTP" -connect $1:25 -starttls smtp
}

check_imap() {
	check_domain "$1 IMAP" -connect $1:993
}

. /etc/certwatch/checks.sh

if [[ "$PASS" != 1 ]]; then
	exit 2;
fi

exit 0;
