#!/bin/bash
#
# ::copy::
# ::maintainer::
#
export CMD=`basename $0`

export CONFDIR=/etc/kusa
export LANG="C"

tmpdir=`mktemp -d /tmp/$CMD-XXXXX`

cleanup()
{
	rm -rf $tmpdir
}
trap "echo '*INTR*'; cleanup; exit 255" 1 2 3
trap "cleanup" EXIT

usage()
{
	echo "usage: $CMD [ldapoptions] {inputfile | -}" >&2
	exit 1
}

# search admin dn and password
#
admin_dn=`kusa-conf ldap.admin`	|| exit 1

if [ -f /etc/ldap.secret ]
then
	admin_pw="-y /etc/ldap.secret"	# use stored password
else
	if admin_pw=`kusa-conf ldap.admin_password 2>/dev/null`
	then
		admin_pw="-w $admin_pw"
	else
		admin_pw="-W"			# ask for password
	fi
fi

# argument must be an input filename or '-' for stdin
# (which is copied to a tempfile then processed)
#
[ $# = 0 ] && usage

if [ X"$1" = "X-" ]
then
	inputfile=$tmpdir/inputfile
	cat >$inputfile || exit 1
else
	[ -f "$1" ] || {
		echo "input file '$1' not found" >&2
		exit 1
	}
	inputfile="$1"
fi

# updates must be done in 3 stages:
# 1. ldapadd that adds non existing entries from tempfile
# 2. the errors file from ldapadd is modified so any entry in this
#    file will be deleted and replaced
# 3. ldapmodify that do the delete and replace job
#
ldapadd -x -D "$admin_dn" $admin_pw -f $inputfile -c -S $tmpdir/modfile || {
	status=$?
	if [ -s $tmpdir/modfile ]
	then
		sed -e 's/^dn: .*/&\nchangetype: delete\n\n&\nchangetype: add/' -i $tmpdir/modfile
		ldapmodify -x -D "$admin_dn" $admin_pw -f $tmpdir/modfile -c -S $tmpdir/errfile
	else
		echo "something goes wrong with 'ldapadd', status=$status" >&2
		exit $status
	fi
}

[ -s $tmpdir/errfile ] && {
	echo "errors occured during update!" >&2
	echo "broken entries left in $tmpdir/errfile" >&2
	rm -f $tmpdir/addfile
	exit 1
}

#cleanup
exit 0
