#!/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/slapindex ]; 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-h" -o x$1 = "x--help" ]; then
	echo "USAGE: Indexes LDAP databases"
	echo "Main database: zmslapindex <key>"
	echo "Config database: zmslapindex -c <key>"
	echo "Accesslog database: zmslapindex -a <key>"
	exit 1
fi

D=`date +%Y%m%d%H%M%S`
CONFIG=no
ALOG=no
if [ x$1 = "x-c" ]; then
	CONFIG=yes
	KEY=$2
elif [ x$1 = "x-a" ]; then
	ALOG=yes
	KEY=$2
else
	KEY=$1
fi

if [ x$CONFIG = "xyes" ]; then
	/opt/zimbra/common/sbin/slapindex -q -F /opt/zimbra/data/ldap/config -n 0 $KEY
	RETVAL=$?
elif [ x$ALOG = "xyes" ]; then
	/opt/zimbra/common/sbin/slapindex -q -F /opt/zimbra/data/ldap/config -b "cn=accesslog" $KEY
	RETVAL=$?
else
	/opt/zimbra/common/sbin/slapindex -q -F /opt/zimbra/data/ldap/config -b "" $KEY
	RETVAL=$?
fi

exit $RETVAL
