#!/bin/bash
# SPDX-FileCopyrightText: 2004-2026 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

PATH=/usr/sbin:/usr/bin:/sbin:/bin

rv=0 tmp=$(mktemp)
cleanup () {
	rm -f "$tmp"
}
trap cleanup EXIT
exec 3>&1 >"$tmp" 2>&1

# shellcheck source=/dev/null
. /usr/share/univention-lib/ucr.sh
if ! is_ucr_false ssl/validity/check
then
	univention-certificate-check-validity || rv=$?
fi

check_gen_crl () {
	local interval crl='/etc/univention/ssl/ucsCA/crl/crl.pem'
	[ "$(ucr get server/role)" = domaincontroller_master ] || return 0
	interval=$(ucr get ssl/crl/interval)
	[ "${interval:-0}" -ge 1 ] || return 0
	[ -f "$crl" ] && [ -n "$(find "$crl" -mtime "-$interval")" ] && return 0
	# shellcheck source=../make-certificates.sh
	. /usr/share/univention-ssl/make-certificates.sh
	gencrl
}
check_gen_crl || rv=$?

if [ "$(ucr get server/role)" = domaincontroller_master ]; then
	if ! is_ucr_false ssl/update/expired; then
		univention-certificate update-expired
	fi
fi

[ 0 -eq $rv ] || cat "$tmp" >&3
exit $rv
