#!/bin/sh
#
#ident        "@(#)idxgen.sh	1.16 01/06/06  
#
#Copyright 08/06/97 Sun Microsystems, Inc. All Rights Reserved
#

#
#Update LDBM database indexes
#

trap 'echo "$0: Interrupted "; exit 1' INT QUIT
USAGE="Usage: `basename $0` [backend_directory] [-a attribute_name [attribute_name...]]"
BASEDIR=`/bin/pkgparam SUNWsds BASEDIR 2>/dev/null`
if [ -z "$BASEDIR" ]    # pkg not installed
then
        BASEDIR=/opt    # set default
fi

LDBMCAT=$BASEDIR/SUNWconn/ldap/sbin/ldbmcat
LDIFINDEX=$BASEDIR/SUNWconn/ldap/lib/ldif2index
LDIFLDBM=$BASEDIR/SUNWconn/ldap/sbin/ldif2ldbm
LDIFFILE=/tmp/ldif.tmp$$.
ETCDIR=$BASEDIR/SUNWconn/ldap/lib
SLAPDCONF=/etc/opt/SUNWconn/ldap/current/slapd.conf
BASENAME=`/usr/bin/basename $0`
DIRNAME=`/usr/bin/dirname $0`
REFRESH=$DIRNAME/$BASENAME
GREP=/usr/xpg4/bin/grep
CAT=/bin/cat
LS=/bin/ls
AWK=/bin/awk
RM=/bin/rm
TEST=/bin/test
NICE=/bin/nice

NICE_LEVEL=-10
COUNT=0

#
# Refresh indexes of a given LDBM backend
#

refresh() {

# generate LDIF file

	DBDIR=$1

	#backslash the slash
	BSDBDIR=`echo $DBDIR | sed -e 's/\//{\\\}/g' |sed -e 's/{//g' | sed -e 's/}/\//g' `

	$TEST -f "$LDIFFILE$COUNT" && $RM "$LDIFFILE$COUNT"
	$LDBMCAT $DBDIR/id2entry.dbb > $LDIFFILE$COUNT

	# Get ldbm backend index in slapd.conf file
	DBNUM=`$CAT $SLAPDCONF | $GREP "directory" | $CAT -n | $GREP "$DBDIR" | $AWK '{ print $1 }'`
	if [ "$DBNUM" -eq 1 ]
	then 
		DBNUM=""
	else
		DBNUM="-n $DBNUM"
	fi

	if [ "$ATTLIST" ] 
	then

		# Extract index list for that backend
		# i.e all indexes between 2 <suffix> tokens

		for idx in `$CAT $SLAPDCONF | $GREP -E 'database|index|directory' | $AWK "/^directory[ 	]*$BSDBDIR/ { flag = 1 ; while ( flag = 1 ) { getline; if ( \\$1 != \"index\" ) { exit } else { print \\$2 } } } "`
		do

		# attribute separeted by commas

			for index in `echo $idx | $AWK " BEGIN { FS=\",\" } { for ( i = NF; i> 0; --i) print \\$i }  END {} "`
			do
				# regenerate index

				ETL=`echo $ATTLIST | grep -i -w $index`
				if [ "$ETL" ]
				then 
					echo Index $index...
					$RM -f $DBDIR/$index.dbb
					$NICE $NICE_LEVEL $LDIFINDEX -i $LDIFFILE$COUNT -f $SLAPDCONF $DBNUM $index &
				fi
			done
		done
	else
		echo all indexes...
		$NICE $NICE_LEVEL $LDIFLDBM -c -i $LDIFFILE$COUNT -f $SLAPDCONF -j 10 $DBNUM -e $ETCDIR &
	fi

	COUNT=`expr $COUNT + 1`
}

#
# main
#


ATTFOUND=0
ATTLIST=""
DBNAME="_"

for i
do
	if [ "$i" = "-a" ]
	then
		if [ "$ATTFOUND" = 1 ]
		then
			echo "$USAGE"
			exit 1
		else 
			ATTFOUND=1
		fi
	else if [ "$ATTFOUND" = 1 ]
		then
			ATTLIST="$ATTLIST $i"
		else if [ "$DBNAME" = "_" ]
			then
				DBNAME=$i
			else
				echo "$USAGE"
				exit 1
			fi
		fi
	fi
done

if [ "$DBNAME" = "_" ]
then
	#refresh all ldbm backends
	for i in `$CAT $SLAPDCONF | $GREP 'directory' | $AWK " { print \\$2 } END {} "`
	do
		echo Regenerating indexes for datastore $i ...
		refresh $i
	done
else
	echo Regenerating indexes for datastore $1 ...
        refresh $DBNAME 
fi

wait
for i in `$LS /tmp/ldif.tmp*`
do
	$RM -f $i 
done
exit 0
