#!/bin/bash
# vi(1) :se tabstop=2

# default values:
myCERTBOT_DEFAULT_EMAIL='Michael Paoli <Michael.Paoli@berkeley.edu>'
#myCERTBOT_RSA_KEY_SIZE=${myCERTBOT_RSA_KEY_SIZE:-4096}
myCERTBOT_RSA_KEY_SIZE=${myCERTBOT_RSA_KEY_SIZE:-2048}

# Take arguments(s) to be sets of cert names,
# each set comma (,) separated set of one or more cert names.
# For each set, generate cert, if set has multiple comma (,) separated
# names, use first for CN, and Subject Alternative Name (SAN) for all in
# the set

# Use default email if myCERTBOT_EMAIL is unset,
# but if it's null, leave it null.
myCERTBOT_EMAIL=${myCERTBOT_EMAIL-$myCERTBOT_DEFAULT_EMAIL}

# If myCERTBOT_EMAIL is null (or unset),
# add --register-unsafely-without-email to our options.
[ -n "$myCERTBOT_EMAIL" ] ||
myCERTBOT_OPTS="${myCERTBOT_OPTS:+$myCERTBOT_OPTS }--register-unsafely-without-email"

umask 077 || exit
LC_ALL=C export LC_ALL
rc=0

[ "$#" -ge 1 ] || {
	1>&2 echo "usage $0: certset [ certset ... ]"
	exit 1
}

trapsigs='1 2 3 15'
gotsig=
for sig in $trapsigs
do
	trap "gotsig=$sig" "$sig"
done
GETCERTS_TMPF="$(mktemp)" ||
	exit 1
export GETCERTS_TMPF ||
	exit 1
for sig in $trapsigs
do
	trap '
		cat "$GETCERTS_TMPF" |
		while read -r CERTBOT_DOMAIN CERTBOT_VALIDATION CERTBOT_TOKEN x
		do
			export CERTBOT_DOMAIN CERTBOT_VALIDATION CERTBOT_TOKEN
			/home/mycert/bin/mymanual-cleanup-hook
		done
		rm "$GETCERTS_TMPF"
		trap - 0 '"$trapsigs"'
		kill -'"$sig"' "$$"
	' "$sig"
done
trap '
	rm "$GETCERTS_TMPF"
	trap - 0
	exit "$rc"
' 0

for certset
do
	{
		>"$GETCERTS_TMPF" &&
		. ~mycert/bin/.GenCSRs.common &&
		unset CERTBOT_TOKEN &&
		certbot \
			certonly \
			--agree-tos \
			--config "$HOME"/etc/letsencrypt/cli.ini \
			--config-dir "$HOME"/etc/letsencrypt \
			--csr "$csrfile" \
			--duplicate \
			${myCERTBOT_EMAIL:+--email "$myCERTBOT_EMAIL"} \
			--force-renewal \
			--logs-dir "$HOME"/var/log/letsencrypt \
			--manual \
			${myCERTBOT_PREFERRED_CHAIN:+--preferred-chain "$myCERTBOT_PREFERRED_CHAIN"} \
			--no-eff-email \
			--rsa-key-size "$myCERTBOT_RSA_KEY_SIZE" \
			--work-dir "$HOME"/var/lib/letsencrypt \
			$myCERTBOT_OPTS
	} \
	|| rc=1
done
exit "$rc"
