#!/bin/sh


# Set the UMASK so permissions are more open
umask 022

# Path to postgres installation
export PG_INSTALL=/usr/local/pg82
export PG_VERSION=8.2.4

# Install needed binaries
apt-get install update-inetd bzip2 patch cvs build-essential bin86 zlib1g-dev libreadline5-dev make gcc flex bison


# Download Postgres
cd /usr/local/src/
wget ftp://ftp.de.postgresql.org/mirror/postgresql/source/v${PG_VERSION}/postgresql-${PG_VERSION}.tar.bz2
tar -xjvf postgresql-${PG_VERSION}.tar.bz2


# Prepare the groups and the postgres user.
# No need to do it if you already have postgres installed


groupadd web
useradd -g web -m -d ${PG_INSTALL} postgres
chown -R postgres.web ${PG_INSTALL} 
chown -R postgres.web /usr/local/src/postgresql-${PG_VERSION}
chmod 750 ${PG_INSTALL}



# Add the path for the postgres user
echo "export PATH=$PG_INSTALL/bin/:${PATH}" >> ${PG_INSTALL}/.profile
echo "export LD_LIBRARY_PATH=${PG_INSTALL}/lib:${LD_LIBRARY_PATH}" >> ${PG_INSTALL}/.profile



# And install it into the defined directory
su - postgres -c "cd /usr/local/src/postgresql-${PG_VERSION} && ./configure --prefix=${PG_INSTALL}"
su - postgres -c "cd /usr/local/src/postgresql-${PG_VERSION} && make all"
su - postgres -c "cd /usr/local/src/postgresql-${PG_VERSION} && make install"


# Link the postgres installation
rm -f /usr/local/pgsql
ln -s $PG_INSTALL /usr/local/pgsql

# make sure postgres starts automatically
cvs -d :pserver:anonymous@cvs.openacs.org:/cvsroot co openacs-4/packages/acs-core-docs/www/files/postgresql.txt
cp openacs-4/packages/acs-core-docs/www/files/postgresql.txt /etc/init.d/pg82
chown root.root /etc/init.d/pg82
chmod 755 /etc/init.d/pg82
update-rc.d pg82 defaults
rm -r openacs-4/

# Link it up to be "backwards compatible"
rm -f /etc/init.d/postgresql
ln -s /etc/init.d/pg82 /etc/init.d/postgresql