#!/bin/bash

BKP_DIR="/var/backups/eehosting-backup/ldap"
DATE=$(date +%Y%m%d%H%M)
BKP_DAYS=0
EXIT_CODE=0
SLAP_OPTS="-o ldif-wrap=no"

# checks
[ $EUID -eq 0 ] || { echo Must be launched by root >&2; exit 1; }
mkdir -p -m 750 $BKP_DIR || { echo Unable to mkdir $BKP_DIR >&2; exit 1; }
cd $BKP_DIR || { echo Unable to cd in $BKP_DIR >&2; exit 1; }
chown openldap:openldap $BKP_DIR

# cleanup
find -maxdepth 1 -mtime +$BKP_DAYS -delete || MSG="$MSG\nUnable to purge old dumps"
if [ $? -ne 0 ]
then
    echo "Unable to purge old dumps" >&2
    EXIT_CODE=1
fi


SLAPD_CONF=/etc/ldap/slapd.conf
if [ -d /etc/ldap/slapd.d ]
then
	SLAPD_CONF=/etc/ldap/slapd.d
fi

# From slapd.preinst
get_all_slapd_conf_files() {                                            # {{{
# Returns the list of all the config files: slapd.conf and included files.
        echo ${SLAPD_CONF}
        awk '
BEGIN { I=0 } 
/^include/ {
        sub(/include/," ");
        I=1;
} 
I==1 && /^[ \t]+/ { 
        split($0,F) ;
        for (f in F) 
                if (!match(F[f],/schema/)) { 
                        print F[f]
                } ;
        next;
}
I==1 { I=0 }
' ${SLAPD_CONF}
}

get_suffix() {                                                          # {{{
        if [ -f "${SLAPD_CONF}" ]; then
                for f in `get_all_slapd_conf_files`; do
                        sed -n -e '/^suffix[[:space:]]/ { s/^suffix[[:space:]]\+"*\([^"]\+\)"*/\1/; s/\\\\/\\/g; p }' $f
                done
        else
                grep -h ^olcSuffix ${SLAPD_CONF}/cn\=config/olcDatabase*.ldif | cut -d: -f 2
        fi | sort -u
}

SUFFIXES=$(get_suffix)

[ -z "$SUFFIXES" ] && { echo "No suffixes found!" >&2 ; exit 1; }

[ -d $SLAPD_CONF ] && SUFFIXES="$SUFFIXES cn=config"

for suffix in $SUFFIXES
do
	backup_file="$BKP_DIR/${suffix}_${DATE}.ldif"
	su - openldap -s /bin/sh -c "/usr/sbin/slapcat ${SLAP_OPTS} -b $suffix -l $backup_file"
	if [ $? -ne 0 ]
	then
		echo "Error dumping $suffix: $!" >&2
		EXIT_CODE=1
        continue
	fi
    gzip "$backup_file"
	if [ $? -ne 0 ]
	then
		echo "Error compressing $backup_file: $!" >&2
		EXIT_CODE=1
	fi
done

exit $EXIT_CODE
