#!/bin/bash -e
#
# Univention Directory Notifier
#  Replicate many DN
#
# SPDX-FileCopyrightText: 2012-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

eval "$(ucr shell)"

usage()
{
	echo "Usage: $0 <file name>"
	echo
	echo "The DNs in the given file will be re-replicated by the Univention Directory Notifier to all UCS systems in this UCS domain. This tool must be run on the Primary Directory Node."
	echo
	echo "Warning: This tool will stop the OpenLDAP and the Notifier daemon."
	echo
}

if [ "$server_role" != "domaincontroller_master" ]; then
	echo "Abort: This tool must be run on the Primary Directory Node!" >&2
	exit 1
fi

if [ ! -e /var/lib/univention-ldap/notify/transaction ]; then
	echo "Abort: /var/lib/univention-ldap/notify/transaction was not found." >&2
	exit 1
fi

dnfile="$1"

if [ -z "$dnfile" ]; then
	usage >&2
	exit 1
fi

if [ ! -r "${dnfile}" ]; then
	echo "${dnfile} is not readable" >&2
	exit 1
fi

RESTART_NOTIFIER=0
if pidof univention-directory-notifier >/dev/null ; then
	echo -n "Stopping notifier: "
	RESTART_NOTIFIER=1
	systemctl stop univention-directory-notifier
	sleep 1
	if pidof univention-directory-notifier >/dev/null ; then
		echo "failed"
		echo "Abort: Failed to stop the notifier daemon. Please check stop the daemon manually and try again." >&2
		exit 1
	fi
	echo "done"
fi

RESTART_SLAPD=0
if pidof slapd >/dev/null ; then
	echo -n "Stopping slapd: "
	RESTART_SLAPD=1
	systemctl stop slapd
	sleep 1
	if pidof slapd >/dev/null ; then
		echo "failed"
		echo "Abort: Failed to stop the OpenLDAP daemon. Please check stop the daemon manually and try again." >&2
		exit 1
	fi
	echo "done"
fi

echo -n "Write $(sed '/^\s*$/d' "${dnfile}" | wc -l) DNs to listener file: " # don't count blank lines
id="$(tail -n 1 /var/lib/univention-ldap/notify/transaction | awk '{print $1}')"

last_line="$(tail -n 1 /var/lib/univention-ldap/listener/listener)"
if [ -n "$last_line" ]; then
	id_listener="$(awk '{print $1}' <<<"$last_line")"
fi

if [ -n "$id_listener" ] && [ "$id_listener" -gt "$id" ]; then
	nextid=$((id_listener+1))
else
	nextid=$((id+1))
fi

skip=''
while read -r dn; do
	if [ -n "$dn" ] && slapdn -f /etc/ldap/slapd.conf "$dn" > /dev/null 2>&1; then
		echo "$nextid $dn m" >>/var/lib/univention-ldap/listener/listener
		echo -n "$nextid" >/var/lib/univention-ldap/last_id
		nextid=$((nextid+1))
	else
		# shellcheck disable=SC1117
		test -n "$dn" && skip="${skip}Info: Skipped invalid dn '$dn'\n"
	fi
done < "${dnfile}"
echo "done"
echo -ne "$skip" >&2

rc=0
if [ "$RESTART_SLAPD" = 1 ]; then
	echo -n "Starting slapd: "
	if systemctl start slapd; then
		echo "done"
	else
		echo "failed"
		rc=1
	fi
fi

if [ "$RESTART_NOTIFIER" = 1 ]; then
	echo -n "Starting notifier: "
	if systemctl start univention-directory-notifier; then
		echo "done"
	else
		echo "failed"
		rc=1
	fi
fi

exit $rc
