#!/bin/bash +e

#===========[ config ]============#
DEBUG=0
INTERVAL=30
PID_FILE=/var/run/opsiconfd/opsiconfd.pid
#=================================#

check_univention_backend() {
	UCSBACKEND=$(grep "^backend" /etc/opsi/backendManager/dispatch.conf | grep "univention")
	if [ "$UCSBACKEND" != "" ]; then
		[ "$DEBUG" = "1" ] && echo "Checking if ldap password and machine.secret are equal." | logger -p daemon.debug -t opsiconfd-guard
		password=$(grep "^password" /etc/opsi/backends/univention.conf 2>/dev/null | cut -d '"' -f2)
		LDAP_SECRET=$(cat /etc/machine.secret)
		if [ "$password" != "$LDAP_SECRET" ]; then
			echo "Need to update univention backend config, restarting opsiconfd." | logger -p daemon.error -t opsiconfd-guard
			sed -i "s/^password\s*=.*/password = \"${LDAP_SECRET}\"/" /etc/opsi/backends/univention.conf
			/etc/init.d/opsiconfd restart
		fi
	fi
}

start_opsiconfd() {
	echo "opsiconfd not running, starting opsiconfd." | logger -p daemon.error -t opsiconfd-guard
	/etc/init.d/opsiconfd start
}

start_loop() {
	sleep 20
	while true; do
		[ -e /etc/opsi/backends/univention.conf -a -e /etc/machine.secret ] && check_univention_backend
		PID=$(cat $PID_FILE 2>/dev/null)
		if [ "$?" != "0" ]; then
			[ "$DEBUG" = "1" ] && echo "opsiconfd pid-file not found." | logger -p daemon.debug -t opsiconfd-guard
			start_opsiconfd
		else
			[ "$DEBUG" = "1" ] && echo "pid of opsiconfd: $PID" | logger -p daemon.debug -t opsiconfd-guard
			if [ ! -d "/proc/$PID" ]; then
				start_opsiconfd
			fi
		fi
		sleep $INTERVAL
	done
}

if [ "$1" = "daemon" ]; then
	start_loop
else
	exe=$0
	if [ "${exe:0:1}" = "." ]; then
		exe=$(pwd)${exe:1}
	fi
	# prevent blocking umounts
	cd /
	# fork daemon
	$exe daemon </dev/null >/dev/null 2>/dev/null &
fi

