#!/bin/sh
# $FreeBSD: branches/RELEASE_8_4_0/www/openacs/files/adjust_pgsql_conf.sh.in 300897 2012-07-14 14:29:18Z beat $
#
# This script modifies the default "postgresql.conf" in PostgreSQL 8.1 and 8.2
# installations, to suit the needs of OpenACS / .LRN
#
# Manual instructions: 
# http://openacs.org/xowiki/How_to_install_in_Postgres_8.x
#
# Usage: adjust_pgsql_conf.sh [path_to_postgresql.conf]
#
PGUSER=pgsql
LOCALBASE=/usr/local
#
AWK=/usr/bin/awk
CP=/bin/cp
GREP=/usr/bin/grep
PW=/usr/sbin/pw
SU=/usr/bin/su

# Check if PostgreSQL version is >= 8.1.0
if ! `${LOCALBASE}/bin/postmaster -V | ${AWK} -F '[ .]' '{if ($3==8 && $4>=1) {exit 0} else {exit 1}}'`; then
	echo "You need PostgreSQL server 8.1 or higher installed."
	exit 1
fi

# Check if user supplied a path or look for default postgresql.conf
if [ "x${1}" = "x" ]; then
	PGCONF=`${PW} usershow ${PGUSER} | ${AWK} -F: '{ print $9 }'`/data/postgresql.conf
else
	PGCONF=${1}
fi

if ! [ -f "${PGCONF}" ]; then
	echo "ERROR: no such file: ${PGCONF}"; echo ""
	echo "Maybe you use a different datadir or your database is not yet initialized"
	echo "You can initialize your database with:"
	echo "${LOCALBASE}/etc/rc.d/postgresql initdb"; echo ""
	echo "Usage: $0 [path_to_postgresql.conf]"
	exit 1
fi

# Very simple check if the file is a standard PostgreSQL configuration file
if ! `${GREP} -qe '^# PostgreSQL configuration file' ${PGCONF}`; then
	echo "ERROR: ${PGCONF} doesn't appear to be a default PostgreSQL database configuration file"
	exit 1
fi

echo "Found ${PGCONF}"
echo -n "Checking ... "

MODIFY=no
MISSING_FROM=no
REGEX_FLAVOR=no
WITH_OIDS=no

# Check if we need to add anything
if ! `${GREP} -qe '^add_missing_from = on' ${PGCONF}`; then MISSING_FROM=yes; MODIFY=yes; fi
if ! `${GREP} -qe '^regex_flavor = extended' ${PGCONF}`; then REGEX_FLAVOR=yes; MODIFY=yes; fi
if ! `${GREP} -qe '^default_with_oids = on' ${PGCONF}`; then WITH_OIDS=yes; MODIFY=yes; fi

# Backup file and add configuration lines, if necessary
if [ ${MODIFY} = "no" ]; then
	echo "no modifications necessary"
else
	echo "needs to be modified"
	echo "Backing up old configuration file to ${PGCONF}.bak"
	${CP} -p ${PGCONF} ${PGCONF}.bak
	if [ ${MISSING_FROM} = "yes" ]; then echo "add_missing_from = on" >> ${PGCONF}; fi
	if [ ${REGEX_FLAVOR} = "yes" ]; then echo "regex_flavor = extended" >> ${PGCONF}; fi
	if [ ${WITH_OIDS} = "yes" ]; then echo "default_with_oids = on" >> ${PGCONF}; fi
	echo "File successfully modified."
	echo "Please restart your PostgreSQL server (if running)."
fi
