#!/bin/sh -e

certificate_exists=$(cat "${__object:?}/explorer/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="${__object}/explorer/certificate-domains"
			certificate_is_test=$(cat "${__object}/explorer/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
