#!/bin/bash
#
# daily cronjob: automatically renew existing LetsEncrypt certificates
#
# ::do_not_edit::
# ::maintainer::
#
CMD=$(basename $0)
CMDVER="1.4"
CMDSTR="$CMD v$CMDVER (2021-10-24)"

set -u

LOG_TAG="cron-certbot-renew"
notify_email="::certbot.notify_email::"
dry_run=
default_options=

[ $# = 0 ] && default_options="::certbot.options::"

echo "$@" | grep -q -- '--dry-run' && dry_run="-n"


to_syslog()
{
	local line=
	while :
	do
		read line || return 0
		logger "$LOG_TAG $line"
	done
	return 0
}

err_mail()
{
	local retval=$1; shift
	local addr=
	local subj="$CMD error $retval, check /var/log/messages for details"

	logger -t $LOG_TAG "error $retval detected, sending email to $notify_email"

	for addr in $(echo -e "$notify_email" | tr ',' ' ')
	do
		echo -e "$*\n--\n  via $CMDSTR" | mail -s "$subj" $addr
	done
	return 0
}


cd /etc/ssl

out=$(./certbot-auto renew $default_options "$@" 2>&1)
retval=$?
echo "$out" | to_syslog

# 2020.06.03 lc
# - certbot-auto fails but does not exits with error code?
error=false
echo "$out" | grep -q "failed" && error=true

[ $retval != 0 -o "$error" = "true" ] && {
	err_mail $retval "$out"
	exit $retval
}

# run jtinstall with --inform option to detect changes -- exits with 254 status code
# if any file has been installed (new/modified)
#
out=$(jtinstall $dry_run --inform --input "install-certs" --backup /etc/backup 2>&1) 
retval=$?

echo "$out" | to_syslog

case $retval in
  0)	;; # ok
  254)
  	# files installed (new or changed)
	#
	logger -t $LOG_TAG "changes detected, restarting apache"
	/etc/init.d/apache2 restart
	logger -t $LOG_TAG "changes detected, restarting dovecot"
	/etc/init.d/dovecot restart
	logger -t $LOG_TAG "changes detected, restarting postfix"
	/etc/init.d/postfix restart
	;;
  *)	err_mail $retval "$out"
  	exit $retval
  	;;
esac

exit 0
