#!/bin/bash
#
#
#    Scalix Public License
#
#
#    The contents of this file are subject to the Scalix Public License
#    Version 1.1 ("License"); you may not use this file except in
#    compliance with the License. You may obtain a copy of the License at
#
# 
#    http://www.scalix.com/community/licensing 
#
# 
#    Software distributed under the License is distributed on an "AS IS"
#    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
#    the License for the specific language governing rights and limitations
#    under the License.
#
# 
#    The Original Code is Scalix Server. 
#    The Initial Developer of the Original Code is Scalix Corporation. 
#    Copyright (C) 2006 Scalix Corporation. 
#    All Rights Reserved.
#    Additional Copyrights may apply - see the notice in each file
#
#
#
#
#
#
# Reconfigures Postgres and optionally performs any other post-install /
# post-upgrade steps needed.
#
# Designed to be called by the installer after installs and upgrades as the
# very last step before starting the service, so can safely assume that the
# Postgres version written in <INSTALL DIR>/data/PG_VERSION is correct.
#
# Usage: sxpsql-reconfig
#

echo "SCALIX Postgres reconfiguration started."

# If Tomcat or Postgres are running stop them
#
/etc/init.d/scalix-tomcat status | grep 'is running' >/dev/null 2>/dev/null
if [ $? = "0" ]; then
    TOMCAT_RUNNING=1
	/etc/init.d/scalix-tomcat stop
else
    TOMCAT_RUNNING=0
fi

/etc/init.d/scalix-postgres status | grep 'is running' >/dev/null 2>/dev/null
if [ $? = "0" ]; then
    POSTGRES_RUNNING=1
	/etc/init.d/scalix-postgres stop
else
    POSTGRES_RUNNING=0
fi

# Run re-config stuff here -----------------------------------------------------
#
STATUS=0   # returned. Add outcome of each step to this

# Work out PG version
#
GETINSTDIR="/opt/scalix-postgres/bin/sxpsql-get-inst-dir"
PG_VERSION=$($GETINSTDIR)/data/PG_VERSION
if [ ! -r $PG_VERSION ]; then
	echo "Error - file $PG_VERSION is not accessible!"
	exit 1
fi
PG_MAJOR_VER=`cat $PG_VERSION | cut -d'.' -f1`
PG_MINOR_VER=`cat $PG_VERSION | cut -d'.' -f2`

# Make logging changes for all PG versions
#
/opt/scalix-postgres/bin/sxpsql-set-logging -n $PG_MAJOR_VER
let "STATUS += $?"

# Enable DB Auto-VACUUM for all PG versions
#
sleep 1  # to guarantee unique backup config file names
/opt/scalix-postgres/bin/sxpsql-set-vacuum -n $PG_MAJOR_VER $PG_MINOR_VER
let "STATUS += $?"

# Enable DB Auto REINDEX for all PG versions
#
/opt/scalix-postgres/bin/sxpsql-set-reindex
let "STATUS += $?"

#
# Re-config work complete ------------------------------------------------------

# Finally, restore any services which were running
#
[ $POSTGRES_RUNNING -eq 1 ] && /etc/init.d/scalix-postgres start
[ $TOMCAT_RUNNING -eq 1 ] && /etc/init.d/scalix-tomcat start

echo "SCALIX Postgres reconfiguration complete."
exit $STATUS
