#!/bin/bash
#
# ::maintainer::
# ::copy::
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSIG="$CMD v.$CMDVER (2016/10)"

set -e -u

[ $(id -u) != 0 ] && {
	echo -e "\nerror: you need to be root to run this command\n" >&2
	exit 1
}

f_fast=false
[ "X${1:-}" = "X-f" ] && {
	f_fast=true
	shift
}

datadir=$(kusa-conf ldap.datadir)
user=$(stat --format '%U' "$datadir")

# rebuild index fields
#
fields=$(kusa-conf ldap.indexing_fields_eq)
bind_dn=$(kusa-conf ldap.admin)

reindex_cmd="/usr/sbin/slapindex -f /etc/ldap/slapd.conf -b '$bind_dn'"

for fld in $fields
do
	reindex_cmd="$reindex_cmd $fld"
done

if $f_fast
then
	echo "
  running (as user $user):

  # $reindex_cmd
"
else
	echo "
ready to reindex ldap fields, with this command:

  $reindex_cmd

I need to STOP and RESTART ldap server 'slapd' before
reindexing, are you sure to want to proceed?
"
	while :
	do
	  echo -n "yes/no: "
	  read ans
	  case $ans in
	    yes|YES|y|Y|s|S|1) break ;;
	    no|NO|n|N|0) exit 1 ;;
	  esac
	done
fi

/etc/init.d/slapd stop
echo -n " reindexing ... "
DISPLAY= su -s /bin/sh - $user -c "$reindex_cmd"
stat=$?
[ $stat = 0 ] && echo "ok" || echo "ERROR"
/etc/init.d/slapd start

exit $stat
