#! /bin/bash

# $Id: build.sh,v 1.20 2004/08/19 11:35:05 jt Exp $

# vim: tabstop=4

# parse arguments
version=$1
port=$2

# constants
pkg=postgresql

# dir variables
Prefix=/usr
TmpDir=/tmp/$pkg.$$
InstallPrefix=$TmpDir$Prefix

DataDir=$InstallPrefix/share
BinDir=$InstallPrefix/bin
LibDir=$InstallPrefix/lib
ManDir=$DataDir/man
DocDir=$DataDir/doc/$pkg-$version
CygDocDir=$DataDir/doc/Cygwin
PatchDir=CYGWIN-PATCHES
SrcDocDir=doc

# configure
configure --enable-multibyte --with-python --with-perl --with-java --with-CXX --with-openssl --prefix=$Prefix --sysconfdir=/etc --datadir=/usr/share --mandir=/usr/share/man --docdir=$Prefix/share/doc/$pkg-$version

# make
make
make -C contrib

# make install
make DESTDIR=$TmpDir install
make DESTDIR=$TmpDir install-all-headers
make -C contrib DESTDIR=$TmpDir install

# strip executables and DLLs
find $InstallPrefix -name '*.exe' -o -name '*.dll' | xargs strip

# move DLLs from lib to bin
mv $LibDir/*.dll $BinDir

# copy libpostgres.a to lib (FIXME: temporary hack)
cp src/backend/libpostgres.a $LibDir

# convert doc symlinks into "hard" links
find $DocDir -type l | xargs -r ls -l | gawk '{i = NF - 2; print $i, $NF}' |
while read link file
do
	path=$(dirname $link)
	rm -f $link
	ln $path/$file $link
done

# copy Cygwin PostgreSQL README file
mkdir -p $CygDocDir
cp $PatchDir/README $CygDocDir/$pkg-$version.README

# copy PostgreSQL COPYRIGHT, README, etc. files
TopFiles=(COPYRIGHT HISTORY INSTALL README)
DocFiles=(FAQ FAQ_MSWIN KNOWN_BUGS MISSING_FEATURES README.mb.big5 \
	README.mb.jp bug.template)
cp ${TopFiles[*]} ${DocFiles[*]/#/$SrcDocDir/} $DocDir

# create package
tar -C $TmpDir -cjf $pkg-$version-$port.tar.bz2 usr

# remove temporary directory
rm -fr $TmpDir
