#!/bin/sh -e

_explorer_var() {
	grep "^$1:" "${__object:?}/explorer/certificate-data" | cut -d ':' -f 2-
}

certificate_exists="$(_explorer_var certificate_exists)"
name="${__object_id:?}"
state=$(cat "${__object}/parameter/state")

case "${state}" in
	absent)
		if [ "${certificate_exists}" = "no" ]; then
			exit 0
		fi

		echo "certbot delete --cert-name '${name}' --quiet"

		echo remove >> "${__messages_out:?}"
	;;
	present)
		domain_param_file="${__object}/parameter/domain"
		requested_domains=$(mktemp "${TMPDIR:-/tmp}/domain.cdist.XXXXXXXXXX")
		if [ -f "${domain_param_file}" ]; then
			cp "${domain_param_file}" "${requested_domains}"
		else
			echo "$__object_id" >> "${requested_domains}"
		fi

		staging=no
		if [ -f "${__object}/parameter/staging" ]; then
			staging=yes
		fi

		if [ "${certificate_exists}" = "yes" ]; then
			existing_domains=$(mktemp "${TMPDIR:-/tmp}/existing_domains.cdist.XXXXXXXXXX")
			tail -n +4 "${__object:?}/explorer/certificate-data" | grep -v '^$' > "${existing_domains}"
			certificate_is_test="$(_explorer_var certificate_is_test)"

			sort -uo "${requested_domains}" "${requested_domains}"
			sort -uo "${existing_domains}" "${existing_domains}"

			if [ -z "$(comm -23 "${requested_domains}" "${existing_domains}")" ] && \
				[ "${certificate_is_test}" = "${staging}" ]; then
				exit 0
			fi
		fi

		admin_email="$(cat "$__object/parameter/admin-email")"
		webroot="$(cat "$__object/parameter/webroot")"

		cat <<-EOF
		certbot certonly \
			--agree-tos \
			--cert-name '${name}' \
			--email '${admin_email}' \
			--expand \
			--non-interactive \
			--quiet \
			$(if [ "${staging}" = "yes" ]; then
				echo "--staging"
			elif [ "${certificate_is_test}" != "${staging}" ]; then
				echo "--force-renewal"
			fi) \
			$(if [ -z "${webroot}" ]; then
				echo "--standalone"
			else
				echo "--webroot --webroot-path '${webroot}'"
			fi) \
			$(while read -r domain; do
				echo "--domain '${domain}' \\"
			done < "${requested_domains}")
		EOF
		rm -f "${requested_domains}"

		if [ "${certificate_exists}" = "no" ]; then
			echo create >> "${__messages_out}"
		else
			echo change >> "${__messages_out}"
		fi
	;;
	*)
		echo "Unsupported state: ${state}" >&2

		exit 1
	;;
esac
