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

CERTPATH="/etc/univention/ssl/ucsCA/certs"
# shellcheck disable=SC2034
INDEXATTRPATH="/etc/univention/ssl/ucsCA/index.txt.attr"

install -d -m 0755 "$CERTPATH"

# add random id to default SSL common name (Bug #22846)
random_id="$(tr -d -c '[:alnum:]' < /dev/urandom | head -c8)"
country="$(ucr get locale/default | cut -c 4-5)"
univention-config-registry set ssl/country?"${country:-DE}" \
	ssl/state?"${country:-DE}" \
	ssl/locality?"${country:-DE}" \
	ssl/organization?"${country:-DE}" \
	ssl/organizationalunit?"Univention Corporate Server" \
	ssl/common?"Univention Corporate Server Root CA (ID=$random_id)" \
	ssl/email?"ssl@${domainname:-}" \
	ssl/default/days?1825 \
	ssl/validity/warning?30 \
	ssl/validity/check?yes \
	ssl/update/expired?yes \
	ssl/host/objectclass?univentionDomainController,univentionMemberServer,univentionClient \
	ssl/crl/interval?7 \
	ssl/crl/validity?10 \
	ssl/ca/cipher?aes256 \
	ssl/default/hashfunction?sha256 \
	ssl/default/bits?2048

eval "$(univention-config-registry shell)"

# shellcheck source=/dev/null
. /usr/share/univention-lib/base.sh
create_logfile_if_missing /var/log/univention/ssl-sync.log "root:adm" 640
case "${server_role:-}" in
domaincontroller_master|basesystem|'')
	if [ ! -s "$CERTPATH/00.pem" ] && [ ! -e "/etc/univention/ssl/${hostname:-}.${domainname:-}" ]; then

		# try to set the clock before generating the root CA, otherwise it is possible that the certificate is not valid at the end of the installation
		# Bug #13549
		timeout -k 5 15 rdate -n 2.debian.pool.ntp.org ||
			timeout -k 5 15 rdate time.fu-berlin.de ||
			timeout -k 5 15 rdate 130.133.1.10 ||
			true

		# shellcheck source=../make-certificates.sh
		. /usr/share/univention-ssl/make-certificates.sh
		init
		univention-certificate new -name "$hostname.$domainname"
		ln -snf "$hostname.$domainname" "/etc/univention/ssl/$hostname"
	else
		echo "skipped. SSL Certificate found in $CERTPATH"
	fi
	;;
esac

if [ "$1" = "configure" ]
then
	SSL='/usr/local/share/ca-certificates/ucsCA.crt'
	[ ! -e "$SSL" ] &&
		ln -snf "/etc/univention/ssl/ucsCA/CAcert.pem" "$SSL" &&
		update-ca-certificates --fresh

	systemctl try-restart univention-directory-listener
fi

#DEBHELPER#

exit 0
