#! /bin/sh
#
# Prepare a release of libpqxx.  This is tailored to my machine and my current
# postgres installation.  It's not supposed to work on anything else.
#
# Usage: preprelease [sourcedir]
#
# where sourcedir is the main directory of the libpqxx source tree; defaults
# to .
# 
# The script builds libpqxx and runs a regression test from the tarball
# generated by 'make dist'.  This ensures that no important files are left out
# of the distribution archive, and that there are no regression failures in the
# released version.
#
# If successful, the script leaves a distribution tarball in /tmp.
#
# Set CONFIG_ARGS to any argument list you wish to pass to configure

LOGFILE=/tmp/libpqxx-preprelease.log
ERRLOG=/tmp/libpqxx-preprelease.err

SOURCEDIR=$1

function print() {
	echo "$1" >>$LOGFILE
	echo "$1" >>$ERRLOG
}

function log() {
	print
	print "`date`: $1"
	print
}

function command() {
	print "$ $1"
	$2 $1 >>$LOGFILE 2>>$ERRLOG
}

rm -f $LOGFILE $ERRLOG

log "Preparing libpqxx release.  Log file is $LOGFILE, errors go to $ERRLOG"

tail -f --pid=$$ $ERRLOG &

log "Ensuring PostgreSQL is running..."
command startpostgres nice

if test -z "$PGHOST"; then export PGHOST=/tmp; fi

log "Accessing PostgreSQL in $PGHOST"

set -e

if test -z "$SOURCEDIR"; then SOURCEDIR="."; fi
command "cd $SOURCEDIR"

log "Building in \"$SOURCEDIR\" (`pwd`)"

VERSION=`grep AC_INIT configure.ac | cut -d ' ' -f 2 | cut -d ',' -f 1`
log "Preparing release of version $VERSION"
DISTNAME=libpqxx-$VERSION
TARBALL=$DISTNAME.tar.gz

log "Generating autoconf/automake files"
command ./autogen.sh nice

log "Generating reference documentation"
command doxygen nice

log "Generating tutorial"
command "xmlto -o doc/html/Tutorial xhtml doc/libpqxx.xml"

log "Creating $TARBALL"
command "make dist" nice

command "rm -f /tmp/$TARBALL"
command "mv $TARBALL /tmp"

command "cd /tmp"
command "rm -rf $DISTNAME"

log "Extracting $TARBALL in /tmp"
command "tar xzf $TARBALL"
command "rm $TARBALL"
command "cd $DISTNAME"

log "Configuring"
command "./configure $CONFIG_ARGS" nice

log "Building"
command "make" nice

log "Running regression test"
command "make check" nice
grep '^PASS:' $LOGFILE
grep '^FAIL:' $LOGFILE 2>>$ERRLOG || true
grep '^All [0-9]* tests passed' $LOGFILE

log "Creating release version of $TARBALL"
command "make dist" nice
command "mv $TARBALL .."
command "cd .."
command "rm -r $DISTNAME"

log "Finished.  Release tarball is /tmp/$TARBALL"

# Give output time to catch up with command prompt
sleep 2

