#!/bin/bash
#
# sxpsql-set-reindex
#
# Enables Postgres auto-REINDEXing by scheduling 'sxpsql-reindex' to be called
# regularly via cron.
#
# Usage: sxpsql-set-reindex
#

ME=$(basename $0)

# Pull in common routines
#
. /opt/scalix-postgres/bin/common-cron.sh

#------------------------------------------------------------------------------
# writeReindexCrontabEntry                                                    #
#------------------------------------------------------------------------------
# Creates the crontab entry for REINDEX
# Returns:
#	0=OK / 1=ERR
#	If ERR, an error message is passed back via STDOUT
#
writeReindexCrontabEntry() {
	ACCOUNT=$1

	CRONTAB=/tmp/sxpsql-set-reindex-crontab.$$
	ERRS=/tmp/sxpsql-set-reindex-crontab-errs.$$
	TMP=/tmp/sxpsql-set-reindex.$$

	crontab -u $ACCOUNT -l > $CRONTAB 2> $ERRS
	if [ $? -ne 0 -a "$(cat $ERRS)" != "no crontab for $ACCOUNT" ]; then
		echo "Error - Unable to read ${ACCOUNT}'s crontab."
		rm -f $CRONTAB $ERRS
		return 1
	fi
	
	grep "scalix-reindex-start" $CRONTAB > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		# crontab already contains this entry - do nothing
		rm -f $CRONTAB $ERRS
		return 0
	fi
		
	ENTRY="#--scalix-reindex-start ---------------- DO NOT DELETE THIS LINE --
#
# SCALIX - Postgres DB maintenance - regularly REINDEX tables
#
0 5 * * *  /opt/scalix-postgres/bin/sxpsql-reindex -f
#--scalix-reindex-end ------------------ DO NOT DELETE THIS LINE --
"
	echo "$ENTRY" >> $CRONTAB  # add new entry

	# Update the crontab
	crontab -u $ACCOUNT $CRONTAB > $TMP 2> $ERRS
	if [ $? -ne 0 ]; then
		echo "Error - Unable to update ${ACCOUNT}'s crontab: $(cat $ERRS)"
		rm -f $CRONTAB $ERRS $TMP
		return 1
	fi

	rm -f $CRONTAB $ERRS $TMP
	return 0
}


# Main
#
if [ $(whoami) != "root" ]; then
	echo "Please run $ME as root."
	exit 1
fi

echo "SCALIX Postgres auto-reindex reconfiguration started."

ACCOUNT="root"
PG_LOG=$($GETINSTDIR)/pgactivity.log

STATUS_MSG=$(writeReindexCrontabEntry $ACCOUNT)
if [ $? -ne 0 ]; then
	M="*WARNING* - The SCALIX Postgres reconfiguration script could not
		deploy 'sxpsql-reindex' via cron because it could not add an 
		entry to ${ACCOUNT}'s crontab.
		Manual reconfiguration is therefore required if you want to
		run periodic REINDEX commands (recommended)."
	echo "$M" >> $PG_LOG
	echo "$M"
	echo "$STATUS_MSG"   # error message from writeReindexCrontabEntry()
	exit 1
fi

echo "Periodic REINDEX commands enabled via ${ACCOUNT}'s crontab."

echo "SCALIX Postgres auto-reindex reconfiguration completed."
exit 0
