#! /bin/sh

# $Id: activate 46815 2017-07-28 14:23:06Z wsl $
# $URL: https://svn.uvt.nl/its-id/trunk/sources/kiki/bin/activate $

set -e

cd

umask 027

ldapserver=ldap://localhost
ldapbase=dc=example,dc=com
ldaproot=cn=ldaproot,$ldapbase
ldapcreds=$HOME/credentials

. /etc/kiki/activate.cf

exec >debug.out
exec 9>lock

touch watershed

while [ -e watershed ]
do
	if flock -n 9
	then
		if [ -e watershed ]
		then
			rm watershed

			renice 20 $$

			/usr/lib/kiki/export &
			pid=$!

			{
				ldapsearch -LLL -x -H $ldapserver -D "$ldaproot" -y "$ldapcreds" -b "$ldapbase" '(|(objectClass=lookupTable)(objectClass=lookupKey))'
				ldapsearch -LLL -x -H $ldapserver -D "$ldaproot" -y "$ldapcreds" -b "$ldapbase" '(cn=* \(mail alias\))'
			} >old

			wait $pid

			size=$(stat --format=%s ldif)
			case $(( size < 10000000 )) in 1)
				echo "ldif file too small, aborting" >&2
				exit 2
			esac

			ldiff old ldif >changes

			if [ -s changes ]
			then
				ldapmodify -c -x -S errors -H $ldapserver -D "$ldaproot" -y "$ldapcreds" -f changes
			fi
		fi
		flock -u 9
	else
		break
	fi
done
