#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 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/slapadd ]; then
	exit 0
fi

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

zgood=no
bgood=no
zcat=`which zcat 2>/dev/null`
bzcat=`which bzcat 2>/dev/null`

if [ -x $zcat ]; then
	zgood=yes
fi

if [ -x $bzcat ]; then
	bgood=yes
fi

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

CONFIG=no
ALOG=no
if [ x$1 = "x-c" ]; then
	CONFIG=yes
	SRC=$2
elif [ x$1 = "x-a" ]; then
	ALOG=yes
	SRC=$2
else
	SRC=$1
fi

comp=0
computil=

if [ ! -f $SRC ]; then
	echo "Error: Input file does not exist"
	exit 1
fi

if [[ "$SRC" == *".gz" ]]; then
	if [ x$zgood = "xno" ]; then
		echo "Error: zcat is missing."
		exit 1
	fi
	computil=$zcat
	comp=1
elif [[ "$SRC" == *".bz2" ]]; then
	if [ x$bgood = "xno" ]; then
		echo "Error: bzcat is missing."
		exit 1
	fi
	computil=$bzcat
	comp=1
fi

if [ x$CONFIG = "xyes" ]; then
	if [ x$comp = "x0" ]; then
		/opt/zimbra/common/sbin/slapadd -q -F /opt/zimbra/data/ldap/config -n 0 -l $SRC
		RETVAL=$?
	else
		$computil $SRC | /opt/zimbra/common/sbin/slapadd -q -F /opt/zimbra/data/ldap/config -n 0
		RETVAL=$?
	fi
elif [ x$ALOG = "xyes" ]; then
	if [ x$comp = "x0" ]; then
		/opt/zimbra/common/sbin/slapadd -q -F /opt/zimbra/data/ldap/config -b "cn=accesslog" -l $SRC
		RETVAL=$?
	else
		$computil $SRC | /opt/zimbra/common/sbin/slapadd -q -F /opt/zimbra/data/ldap/config -b "cn=accesslog"
		RETVAL=$?
	fi
else
	if [ x$comp = "x0" ]; then
		/opt/zimbra/common/sbin/slapadd -w -q -F /opt/zimbra/data/ldap/config -b "" -l $SRC
		RETVAL=$?
	else
		$computil $SRC | /opt/zimbra/common/sbin/slapadd -w -q -F /opt/zimbra/data/ldap/config -b ""
		RETVAL=$?
	fi
fi

exit $RETVAL
