#!/bin/sh
#
# autocert -- acme-client post-update hooks
#
# Copyright (c) 2026 Jacob R. Edwards <jacob@jacobedwards.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

set -e

# Configuration directory
c=/etc/autocert

err() {
	echo "$@" 1>&2
	exit 1
}

renew() {
	for d in "${@:?handles}"
	do
		acme-client "$d" && echo "$d"
	done
}

hooks() {
	test $# -eq 0 &&
		exit

	awk '
	function run() {
		if (!c)
			return
		if (system(c))
			printf("Autocert command failure: [\n%s\n]", c) > "/dev/stderr"
		c = ""
	}

	BEGIN {
		for (i in ARGV) {
			domains[ARGV[i]] = 1
			delete ARGV[i]
		}
		ARGC = 1
		nl = sprintf("\n")
	}

	/^#/ {
		next
	}

	length($0) && /^[^	 ]/ {
			run()
			p = 0
			for (i = 1; !p && i <= NF; ++i)
				if ($i in domains)
					p = 1
			next
	}

	p {
		c = c substr($0, 2) nl
	}
	END {
		run()
	}' -- "$@" < "$c"/hooks
}

test $# -eq 0 && {
	! test -f "$c"/handles &&
		err "$c/handles: No handles provided"
	set -- $(grep -v '^#' "$c"/handles)
}

hooks $(renew "$@")
