#!/bin/sh
#
# Renew letsencrypt certificates

set -eu

REALM=$(cat /etc/local-ORG/realm) || true

# resolve hostnames of service installed and registered with Redpill
servicehosts() {
	SERVICE=$1; shift
	for binary in "$@"; do
		> /dev/null which -- "$binary" || exit
	done
	cat "/etc/local-REDPILL/$REALM/${SERVICE}host" \
	  "/etc/local-REDPILL/$REALM/${SERVICE}althosts" \
	  2> /dev/null \
	  | perl -0777 -pe 's/\s*\#.*//gm;s/^\s+//;s/\s+$//;s/\s+/|/g'
}
MAILHOSTS=$(servicehosts mail postconf) || true

mailname=$(cat /etc/mailname) || true
fqdn=$(hostname --fqdn)
domain=$(hostname --domain)

# mailhost is either mailname listed as a Redpill mailhost,
# or default Redpill mailhost if mailname equals domain
mailhost=''
case "$mailname" in
  "$MAILHOSTS")
	mailhost=$mailname
	;;
  "$domain")
	mailhost=$(cat "/etc/local-REDPILL/$REALM/mailhost") || true
	;;
esac

# update non-EC mailhost cert if resolvable and not a certdomain
if [ -n "$mailhost" ]; then
	if [ -n "$fqdn" ] && [ "$mailhost" != "$fqdn" ]; then
		extradomains=${extradomains:+$extradomains }$fqdn
	fi
	if [ -n "$domain" ] && [ "$mailhost" != "$domain" ] && [ "$fqdn" != "$domain" ]; then
		extradomains=${extradomains:+$extradomains }$domain
	fi
	if ! grep ^"$mailhost" /etc/dehydrated/domains.txt; then
		dehydrated --cron --domain "$mailhost $extradomains" --algo rsa
	fi
fi

# update certdomain certs
dehydrated --cron "$@"