#!/bin/bash
#
# dumping the LDAP-database with slapcat into /var/backups/ldapdump.ldif
#
# $Id$
#

DUMPDIR=/var/backups/slapd
DUMPFILE=$DUMPDIR/ldapdump.ldif
TMPDUMPFILE=$DUMPDIR/ldapdump_tmp.ldif
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# if no dump catalog exists, make one; else
# check that we have read/write access to it
if [ ! -d "$DUMPDIR" ] ; then 
    mkdir $DUMPDIR
    chmod 0700 $DUMPDIR
else
    if [ ! -r "$DUMPDIR" -o ! -w "$DUMPDIR" ]; then
	echo "No read- and/or writeaccess to $DUMPDIR, bailing out.."
	exit 1
    fi
fi

# Make sure we run alone and clean up the lock when we exit
lockfile-create "$DUMPFILE"
lockfile-touch "$DUMPFILE" &
# Save the PID of the lockfile-touch process
BADGER="$!"
at_exit() {
    kill "$BADGER"
    lockfile-remove "$DUMPFILE"
}
trap at_exit INT TERM EXIT

# do the LDAP-databasedump (slapcat)
if [ -x /etc/init.d/slapd -a -x /usr/sbin/slapcat ]; then
    logger -t ldapdump.sh "stopping slapd to back up the database"
    count=5
    while /etc/init.d/slapd status && [ 0 -gt $count ] ; do
	/etc/init.d/slapd stop
	sleep 1
	count=$(($count - 1))
    done
    /usr/sbin/slapcat -l $TMPDUMPFILE
    SCRETVAL=$?
    logger -t ldapdump.sh "starting slapd after backing up the database"
    slapdstarted=false
    count=5
    while ! /etc/init.d/slapd status && [ 0 -gt $count ]; do
	if /etc/init.d/slapd start ; then
	    slapdstarted=true
	else
	    sleep 1
	fi
	count=$(($count - 1))
    done
    if ! $slapdstarted ; then
	logger -t ldapdump.sh "unable to restart slapd!"
    fi
    if [ ! $SCRETVAL -eq 0 ]; then
	echo "/usr/sbin/slapcat failed, bailing out."
	exit 1
    fi
else
    echo "Either /etc/init.d/slapd or /usr/sbin/slapcat was not executable."
    echo "Bailing out.."
    exit 1
fi

# check that the LDAP-dumpfile is larger than zero, then replace
# the old dumpfile with the new one
if [ -s "$TMPDUMPFILE" ]; then
    if [ -f "$DUMPFILE" ]; then
	if [ ! -w "$DUMPFILE" ]; then
	    echo "We don't have write access to $DUMPFILE, bailing out.."
	    exit 1
	fi
    fi
    mv "$TMPDUMPFILE" "$DUMPFILE"
    echo "Successfully dumped the LDAP-database to $DUMPFILE."
else
    echo "The LDAP-dump was zero-sized, bailing out.."
    exit 1
fi

exit 0
