#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 
ulimit -n 32768
ulimit -c unlimited
ulimit -v unlimited
export LD_PRELOAD=/opt/zimbra/common/lib/libtcmalloc_minimal.so

umask 027
source /opt/zimbra/bin/zmshutil || exit 1
zmsetvars

if [ ! -x /opt/zimbra/common/sbin/slapcat ]; then
	exit 0
fi

u=`id -un`
if [ $u != ${zimbra_user} ]; then
    echo "Error: must be run as ${zimbra_user} user"
    exit 1
fi

if [ x$1 = "x" -o x$1 = "x-h" -o x$1 = "x--help" ]; then
	echo "USAGE: Exports LDAP databases"
	echo "Main database: zmslapcat <DIR>"
	echo "Config database: zmslapcat -c <DIR>"
	echo "Accesslog database: zmslapcat -a <DIR>"
	exit 1
fi

D=`date +%Y%m%d%H%M%S`
CONFIG=no
FILE=ldap.bak.${D}
NFILE=ldap.bak
if [ x$1 = "x-c" ]; then
	CONFIG=yes
	FILE=ldap-config.bak.${D}
	NFILE=ldap-config.bak
	DEST=$2
elif [ x$1 = "x-a" ]; then
	ALOG=yes
	FILE=ldap-accesslog.bak.${D}
	NFILE=ldap-accesslog.bak
	DEST=$2
else
	DEST=$1
fi

mkdir -p $DEST
RC=0
if [ x$CONFIG = "xyes" ]; then
	/opt/zimbra/common/sbin/slapcat -F /opt/zimbra/data/ldap/config -n 0 -l ${DEST}/${FILE}
	RC=$?
elif [ x$ALOG = "xyes" ]; then
	if [ -d /opt/zimbra/data/ldap/accesslog/db ]; then
		/opt/zimbra/common/sbin/slapcat -F /opt/zimbra/data/ldap/config -b "cn=accesslog" -l ${DEST}/${FILE}
		RC=$?
	else
		exit $RC
	fi
else
	/opt/zimbra/common/sbin/slapcat -F /opt/zimbra/data/ldap/config -b "" -l ${DEST}/${FILE}
	RC=$?
fi

cp -f ${DEST}/${FILE} ${DEST}/${NFILE}
exit $RC
