#!/usr/bin/env bash

# The contents of this file are subject to the MonetDB Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://monetdb.cwi.nl/Legal/MonetDBLicense-1.1.html
#
# 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 the MonetDB Database System.
#
# The Initial Developer of the Original Code is CWI.
# Portions created by CWI are Copyright (C) 1997-July 2008 CWI.
# Copyright August 2008-2009 MonetDB B.V.
# All Rights Reserved.

# This shell script gathers the components for a functional complete
# MonetDB/SQL or MonetDB/XQuery version.
# The source files are obtained from the MonetDB website or CVS, if
# not present already.  This script is normally part of the Super Source
# Tarball distribution.
#
# Fabian Groffen <fabian@cwi.nl> -- 2007-01-30
# $Header: /ufs/monet/repository/monetweb/Assets/monetdb-install.sh,v 1.57 2010/10/14 09:10:24 fabian Exp $

show_help() {
	while IFS="" read line; do echo "${line}" > /dev/stderr; done <<EOF
usage: $0 < OPTS ... >

where OPTS are:
   --prefix=path      install into location path, defaults to $HOME/MonetDB
   --build=path       use path as (temporary) build directory, defaults
                      to /var/tmp/MonetDB-XXXXXXXXX
   --enable-sql       build the MonetDB/SQL server
   --enable-xquery    build the MonetDB/XQuery server
   --enable-geom      build geom extension for MonetDB/SQL, this option
                      implies --enable-sql
   --enable-template  build template module for MonetDB extensions, this
                      option requires nightly sources
   --enable-testing   build the MonetDB testing suite necessary for running
                      'make check', Mtest.py or RunMtest
   --nightly=target   download and install a nightly snapshot of the stable
                      or current branch, target must be 'stable' or 'current'
   --enable-debug     compile with debugging support via e.g. gdb
   --enable-optimise  compile with high optimisation flags, enabling this
                      option increases compilation time considerably but
                      often yields in a faster MonetDB server
   --enable-optimize  alias for --enable-optimise
   --package          build a binary package instead of installing the
                      software, this option is not guaranteed to work
                      correctly
   --quiet            suppress output going to stdout
   --help             this message
   --devhelp          special help for developers
   --version          show revision number and quit
EOF
}

show_devhelp() {
	while IFS="" read line; do echo "${line}" > /dev/stderr; done <<EOF
There are a few hooks in this script that may be interesting to
developers or experienced users.

Fetching of sources is by default done with wget.  You can change this
by exporting FETCHCOMMAND to the environment.  Currently FETCHCOMMAND
is set to:
  $FETCHCOMMAND
The default should give you inspiration to change it to use cURL, or ftp
instead if you need it (BSD, Interix, Solaris).  "\$FILE" will expand to
the filename, and "\$URI\" to the url to download.  Both are set when
calling \$FETCHCOMMAND.

If you know what you're doing, by setting EXTRA_ECONF in the environment
you can pass extra arguments to configure invocations.  Use with care.

The variable MAKEOPTS is passed onto each make invocation, and can be
used to e.g. set "-j2" to speed up compilation times.  By setting MAKE,
a make with a special name or location can be used.

When using the --hg option, the variable HGROOTM controls the used
repository to clone from which defaults to:
  http://dev.monetdb.org/hg/MonetDB

Two targets exist which control what the script is doing: unpack and
install.  They can be given as argument to the script.  unpack only
runs the fetch and unpacking phase, while install skips the
fetching/unpacking of the sources, and starts configure/make/make
install.  By using --build=/path/to with the install target it is
possible to resume/retry a (failed) compilation.
EOF
}

if [[ -z $1 ]] ; then
	show_help
	exit -1
fi

# (sane) defaults
PREFIX=$HOME/MonetDB
BUILDROOT=/var/tmp/MonetDB-$(date "+%s")
QUIET=/dev/stdout
ACTION="src_unpack src_compile_install"
DEBUG=
PACKAGE=
: ${FETCHCOMMAND:="wget --progress=dot:mega -t 5 --passive-ftp -O \"\${FILE}\" \"\${URI}\""}

# make sure we get English error messages and so on
export LC_ALL=C

# parse command line options
ORGARG=$*
while [[ -n $1 ]] ; do
	case $1 in
		--prefix=*)
			PREFIX=${1#--prefix=}
		;;
		--build=*)
			BUILDROOT=${1#--build=}
		;;
		--nightly=*)
			NIGHTLY=${1#--nightly=}
			if [[ $NIGHTLY != "stable" ]] && [[ $NIGHTLY != "current" ]] ; then
				echo "--nightly needs either \"stable\" or \"current\" target" > /dev/stderr
				exit -1
			fi
		;;
		--enable-sql)
			DO_SQL=1
		;;
		--enable-xquery)
			DO_XQUERY=1
		;;
		--enable-geom)
			DO_SQL=1
			DO_GEOM=1
		;;
		--enable-template)
			DO_TEMPLATE=1
		;;
		--enable-testing)
			DO_TESTING=1
		;;
		--package)
			# can't set name here, need to have BUILDROOT being
			# processed first
			PACKAGE=yes
			ACTION="${ACTION} pkg_binary"
		;;
		--quiet)
			QUIET=
		;;
		--enable-debug)
			[[ -n $DEBUG ]] && \
				die "you cannot set both --enable-debug and --enable-optimise"
			DEBUG="--disable-optimize --enable-debug --enable-assert"
		;;
		--enable-optimi[sz]e)
			[[ -n $DEBUG ]] && \
				die "you cannot set both --enable-debug and --enable-optimise"
			DEBUG="--enable-optimize --disable-debug --disable-assert"
		;;
		--help)
			show_help
			exit 0
		;;
		--devhelp)
			show_devhelp
			exit 0
		;;
		--version)
			r='$Revision: 1.57 $'
			r=${r#\$Revision: }
			r=${r% \$}
			d='$Date: 2010/10/14 09:10:24 $'
			d=${d#\$Date? }
			d=${d% \$}
			echo "monetdb-install.sh $r (${d//\//-})"
			exit 0
		;;
		# these options are hidden, but pretty much a welcome present
		# for ebuild... ehhh normal developers
		unpack)
			ACTION="src_unpack"
		;;
		compile)
			ACTION="src_compile"
		;;
		install)
			ACTION="src_install"
		;;
		compile_install)
			ACTION="src_compile_install"
		;;
		binary)
			ACTION="pkg_binary"
		;;
		*)
			echo "unknown option $1" > /dev/stderr
			exit -1
		;;
	esac
	shift
done

# check if we can proceed without problems
if [[ -z $DO_SQL && -z $DO_XQUERY ]] ; then
	echo "$0: please tell me what to do, use --enable-sql and/or --enable-xquery"
	exit 0
fi
if [[ -n $DO_TEMPLATE && -z $NIGHTLY ]] ; then
	echo "$0: --enable-template needs --nightly={current,stable}" > /dev/stderr
	exit -1
fi
# go into ebuild mode when requested
[[ -n $ENABLE_EBUILD_MODE ]] && \
	ACTION=${ACTION/src_compile_install/src_compile src_install}

# check paths are writable etc.
if [[ $(mkdir -p "$BUILDROOT") != "" ]] ; then
	echo "$0: failed to create $BUILDROOT" > /dev/stderr
	exit 1
fi
if [[ -z $PACKAGE && -d $PREFIX && ! -w $PREFIX ]] ; then
	echo "$0: cannot write in $PREFIX" > /dev/stderr
	exit 1
elif [[ -z $PACKAGE && ! -d $PREFIX && ! -w ${PREFIX%/*}/ ]] ; then
	echo "$0: cannot create $PREFIX in ${PREFIX%/*}/" > /dev/stderr
	exit 1
fi
if [[ -n $PACKAGE ]] ; then
	PACKAGE=$BUILDROOT/monetdb-$(date +%F)-$(uname)-bin.tar.bz2
fi

# because the configure script will die if Java/Ant are insufficient,
# make sure we know upfront about that to avoid b0rkerage
if type -P javac > /dev/null ; then
	v=$(javac -version 2>&1 | head -n1)
	# if Java ever gets into the 2 major or minors > 9 then we'll have
	# to fix this properly
	if [[ $v == "javac 1."[456789]* ]] ; then
		if type -P ant > /dev/null ; then
			DO_JAVA=source
		else
			{
			echo "$0: warning: cannot build Java jars from source as " \
			echo "    your systems seems not to be equipped with "'`ant`.'
			} > /dev/stderr
		fi
	fi
fi

# to avoid problems with JDBC compilation, make the path we use absolute
BUILDROOT=$(cd "$BUILDROOT" && pwd -P)
# set log location in the buildroot
LOG=$BUILDROOT/log
[[ -z $QUIET ]] && QUIET=$LOG
# default to no optimisation, and no debugging for obvious reasons
[[ -z $DEBUG ]] && \
	DEBUG="--disable-optimize --disable-debug --disable-assert"
# never EVER enable strictness CFLAGS for even more obvious reasons
DEBUG="${DEBUG} --disable-strict"

MAINPID=$$

# functions we frequent lateron 
runifexists() {
	type -P $1 > /dev/null \
		&& "$@" 2>&1 \
		|| echo "$1 cannot be found in the path"
}
die() {
	echo $* > /dev/stderr
	echo "Please refer to the full log at $LOG"
	echo "If you believe this is an error in the script or the software,"
	echo "file a bug and attach the logfile."
	echo >> $LOG
	echo "$(date)" >> $LOG
	echo "The following tools might be relevant to debug your problem:" >> $LOG
	echo '$Revision: 1.57 $' >> $LOG
	runifexists df >> $LOG
	runifexists autoconf --version >> $LOG
	runifexists automake --version >> $LOG
	runifexists libtool --version >> $LOG
	runifexists glibtool --version >> $LOG
	runifexists gcc --version >> $LOG
	runifexists ld --version >> $LOG
	runifexists make --version >> $LOG
	runifexists gmake --version >> $LOG
	runifexists javac -version >> $LOG
	runifexists ant -version >> $LOG
	# python's -V insists on writing to console
	runifexists python -c 'import sys; print sys.version' >> $LOG
	runifexists gawk --version >> $LOG
	runifexists sed --version >> $LOG
	runifexists gsed --version >> $LOG
	# if we are in a subshell, we do not kill the parent by issueing a
	# exit -1... to force hard termination of all actions here, we kill
	# the main process/shell
	kill $MAINPID
	exit -1
}

get_cvs_module() {
	case $1 in
		MonetDB)
			echo "MonetDB"
			return 0
		;;
		MonetDB-buildtools)
			echo "buildtools"
			return 0
		;;
		MonetDB-SQL)
			echo "sql"
			return 0
		;;
		MonetDB-client)
			echo "clients"
			return 0
		;;
		MonetDB4-XQuery)
			echo "pathfinder"
			return 0
		;;
		MonetDB4-server)
			echo "MonetDB4"
			return 0
		;;
		MonetDB5-server)
			echo "MonetDB5"
			return 0
		;;
		MonetDB-geom)
			echo "geom"
			return 0
		;;
		MonetDB-java)
			echo "java"
			return 0
		;;
		MonetDB-template)
			echo "template"
			return 0
		;;
		MonetDB-testing)
			echo "testing"
			return 0
		;;
		*)
			return 1
		;;
	esac
}

fetch() {
	f=${1##*/}
	f=${f%%.*}
	if [[ -n $NIGHTLY || ! -d $f ]] ; then
		LZMA=$(type -P lzma > /dev/null   && echo lzma:lzma)
		BZIP2=$(type -P bzip2 > /dev/null && echo bz2:bzip2)
		GZIP=$(type -P gzip > /dev/null   && echo gz:gzip)
		MD5SUM=$(type -P md5sum)
		GPG=$(type -P gpg)
		# TODO: support md5 (Solaris)
		mkdir "$BUILDROOT"/$f
		for c in $LZMA $BZIP2 $GZIP ; do
			pushd "$BUILDROOT"/$f > /dev/null
			export URI=$1.${c%:*}
			export FILE=${URI##*/}
			eval $FETCHCOMMAND > $QUIET
			ret=$?
			popd > /dev/null
			if [[ $ret == 0 ]] ; then
				if [[ -n $MD5SUM ]] ; then
					pushd "$BUILDROOT"/$f > /dev/null
					export URI=$1.${c%:*}.md5sum
					export FILE=${URI##*/}
					eval $FETCHCOMMAND > $QUIET
					ret=$?
					popd > /dev/null
					if [[ $ret == 0 ]] ; then
						# verify the checksum, if it fails, try another tar
						# can't use md5sum -c, since the name does not
						# have to match (version vs versionless)
						SUM=$(md5sum "$BUILDROOT"/$f/$f.tar.${c%:*} | cut -d' ' -f1)
						RSUM=$(cut -d' ' -f1 "$BUILDROOT"/$f/$f.tar.${c%:*}.md5sum)
						if [[ $SUM == $RSUM ]] ; then
							echo "md5sums match for $f"
							# could use the umd5sum in addition, but I'm lazy
							${c#*:} -d "$BUILDROOT"/$f/$f.tar.${c%:*}
							break
						else
							echo "md5sums do not match for $f, found $SUM, expected $RSUM"
							rm "$BUILDROOT"/$f/$f.tar.${c%:*}
							rm "$BUILDROOT"/$f/$f.tar.${c%:*}.md5sum
						fi
					else
						${c#*:} -d "$BUILDROOT"/$f/$f.tar.${c%:*}
						break
					fi
				else
					# don't have md5sum, assume it's correct
					${c#*:} -d "$BUILDROOT"/$f/$f.tar.${c%:*}
					break
				fi
			fi
		done
		[[ ! -f "$BUILDROOT"/$f/$f.tar ]] && \
			die "fetching $1 {$LZMA,$BZIP2,$GZIP} failed!"
	else
		# we're apparently in a superball distribution
		f=$(pwd)/$f
		pushd "$BUILDROOT" > /dev/null
		# if we symlink, we also "pollute" our sources, but more
		# importantly, the sources may be read-only
		echo "Copying $f to $BUILDROOT" > $QUIET
		cp -pPR "$f" .
		popd > /dev/null
	fi
	return 0
}

econf() {
	local myconf="$(pwd)/configure"
	echo -e "${myconf// --/\n\t--} \n\t--prefix=${PREFIX} ${@/#/\n\t} ${EXTRA_ECONF// --/\n\t--}"  > $QUIET
	if ! ${myconf} --prefix="${PREFIX}" "$@" ${EXTRA_ECONF} > $QUIET ; then
		die "econf failed"
	fi
}

emake() {
	# if user specified MAKE, honour it
	if [[ -z ${MAKE} ]]; then
		# otherwise try to find GNU make...
		if type -P gmake > /dev/null; then
			MAKE=gmake
		elif type -P gnumake > /dev/null; then
			MAKE=gnumake
		elif type -P make > /dev/null; then
			MAKE=make
		else
			echo "unable to find make!" > /dev/stderr
			# leave the dying over to the caller
			MAKE=make
		fi
	fi
	${MAKE} ${MAKEOPTS} "$@" > $QUIET
	return $?
}

src_unpack() {
	local A="MonetDB MonetDB-client"
	[[ -n $DO_JAVA ]] && A="$A MonetDB-java"
	[[ -n $DO_SQL ]] && A="$A MonetDB5-server MonetDB-SQL"
	[[ -n $DO_XQUERY ]] && A="$A MonetDB4-server MonetDB4-XQuery"
	[[ -n $DO_GEOM ]] && A="$A MonetDB-geom"
	[[ -n $DO_TEMPLATE ]] && A="$A MonetDB-template"
	[[ -n $DO_TESTING ]] && A="$A MonetDB-testing"

	NIGHTLYURL=http://monetdb.cwi.nl/testing/projects/monetdb/tars/${NIGHTLY:-release}

	for p in ${A} ; do
		# if sources are in place, assume it is ok (relatively safe, as
		# we have a quite unique $BUILDROOT, so the user gave a dirty
		# --build= if this exists)
		[[ -d $BUILDROOT/$p/$(get_cvs_module $p) ]] && continue
		# ok, fetching is in src_unpack, sorry
		fetch "$NIGHTLYURL/$p.tar"
		if [[ -f $BUILDROOT/$p/$p.tar ]] ; then
			pushd "$BUILDROOT"/$p > /dev/null
			echo "unpacking $p.tar" > $QUIET
			tar -xf $p.tar || die "failed to unpack $p"
			# this is quite ugly, but I don't know how to do it better,
			# first we try to rename in new style (make dist) tarball,
			# followed by an ugly hack for MonetDB[4]-XQuery (people
			# should make up their minds there), then if that fails, we
			# do old style or superball/cvs tarball naming.
			mv $p-[0-9]* $(get_cvs_module $p) > /dev/null 2>&1 || \
			mv ${p/MonetDB4/MonetDB}-[0-9]* $(get_cvs_module $p) > /dev/null 2>&1 || \
			mv $(get_cvs_module $p)-[0-9]* $(get_cvs_module $p) \
				|| die "failed to rename sources to the right name"
			popd > /dev/null
		fi
	done
}

src_compile_install() {
	local A="MonetDB MonetDB-client"
	[[ -n $DO_JAVA ]] && A="$A MonetDB-java"
	[[ -n $DO_SQL ]] && A="$A MonetDB5-server MonetDB-SQL"
	[[ -n $DO_XQUERY ]] && A="$A MonetDB4-server MonetDB4-XQuery"
	[[ -n $DO_GEOM ]] && A="$A MonetDB-geom"
	[[ -n $DO_TEMPLATE ]] && A="$A MonetDB-template"
	[[ -n $DO_TESTING ]] && A="$A MonetDB-testing"

	# make what we build available to the packages that depend on the
	# others, like sql, pathfinder
	export PATH=$PREFIX/bin:$PATH
	export LDFLAGS
	export CFLAGS
	# unpatched autoconf defaults to "lib" as libdir
	export PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig:$PKG_CONFIG_PATH
	if [[ -n $PACKAGE ]] ; then
		D="$BUILDROOT/image"
		PATH=$BUILDROOT/image$PREFIX/bin:$PATH
		case $(uname) in
			Linux|*BSD|SunOS)
				# ELF-based systems
				# prepare for copying in libs later
				LDFLAGS="-Wl,-rpath=$PREFIX/lib/MonetDB/external $LDFLAGS"
				# make sure we can find indirect links to libs during
				# building
				LDFLAGS="-Wl,-rpath-link=$BUILDROOT/image$PREFIX/lib $LDFLAGS"
				# temp workaround for bug #2690
				LDFLAGS="-Wl,-rpath-link=$BUILDROOT/image$PREFIX/lib/MonetDB5/lib $LDFLAGS"
			;;
			Darwin)
				# Darwin searches indirect links, through the normal
				# search path, so nothing we have to do here
				:
			;;
		esac
	fi

	for p in ${A} ; do
		pushd "$BUILDROOT/$p/$(get_cvs_module $p)" > /dev/null
		myconf="./configure --prefix='$PREFIX' $DEBUG $EXTRA_ECONF"
		echo " * Processing $p" > $QUIET
		echo $myconf > $QUIET
		eval "$myconf" > $QUIET || die "configuring $p failed"
		emake || die "making $p failed"
		if [[ -n $PACKAGE ]] ; then
			emake DESTDIR="${D}" install || die "installing $p failed"

			# libtool files cause problems here, because they refer to
			# the actual install location, luckily we don't need them in
			# the first place anyway
			find "${D}" -name "*.la" -delete

			# can't rely on the names here, they don't match in any way
			case $p in
				MonetDB)
					tool=monetdb-config
				;;
				MonetDB-client)
					tool=monetdb-clients-config
				;;
				MonetDB4-server)
					tool=monetdb4-config
				;;
				MonetDB5-server)
					tool=monetdb5-config
					# temp workaround for bug #2690
					LDFLAGS="-L$BUILDROOT/image$PREFIX/lib/MonetDB5/lib $LDFLAGS"
				;;
				*)
					tool=
				;;
			esac
			# add flags so the next run will not just find monetdb
			# config, but also the compiler and linker will find the
			# right headers and libraries
			if [[ -n $tool ]] ; then
				flags=$($BUILDROOT/image/$PREFIX/bin/$tool --cflags)
				ldflags=$($BUILDROOT/image/$PREFIX/bin/$tool --libs)
				CFLAGS="${flags//-I/-I$BUILDROOT/image} $CFLAGS"
				LDFLAGS="${ldflags//-L/-L$BUILDROOT/image} $LDFLAGS"
			fi
		else
			emake install || die "installing $p failed"
		fi
		popd > /dev/null
	done
}

pkg_binary() {
	[[ -z $PACKAGE ]] && die "cannot make binpkg without PACKAGE"
	# at this point, we have everything built in $BUILDROOT/image/
	# the simplest way here is to tar everything up, but that will only
	# work in the most trivial case of almost identical systems (e.g.
	# the same distribution)
	local scantool=
	case $(uname) in
		Linux|*BSD|SunOS)
			scantool=scanelf
		;;
		Darwin)
			scantool=scanmacho
		;;
	esac
	if [[ -z $scantool ]] || ! type -P $scantool > /dev/null ; then
		echo "warning: ${scantool:-scanelf} unavailable, binary package will not include necessary libraries"
	else
		mkdir -p $BUILDROOT/image$PREFIX/lib/MonetDB/external
		if [[ $scantool == scanelf ]] ; then
			# ELF: this really suxors, because we need to mimic the
			# runtime search path to figure out where the fsck stuff
			# resides, we exclude the hosts paths here, because we never
			# want to copy stuff from them anyway (and it's hard to
			# figure out what/where the multilib dirs are)
			(
				$scantool -BRyF "%F:%n" $BUILDROOT/image | while read line ; do
					filename=${line%%:*}
					needed=${line#*:}
					for n in ${needed//,/ } ; do
						echo $n
					done
				done
			) | sort | uniq > $BUILDROOT/needed.elf
			(
				$scantool -BRyF "%F,%r" $BUILDROOT/image | while read line ; do
					filename=${line%%,*}
					needed=${line#*,}
					for n in ${needed//:/ } ; do
						echo $n
					done
				done
			) | sort | uniq > $BUILDROOT/runpath.elf
			# match all needed objects against the paths
			echo "including dependant libs into the image"
			for lib in $(<$BUILDROOT/needed.elf) ; do
				included=
				echo -n "- $lib... "
				echo -n "searching... "
				for path in $(<$BUILDROOT/runpath.elf) ; do
					if [[ -e $path/$lib ]] ; then
						echo -n "processing... "
						if [[ $path == $PREFIX/* ]] ; then
							echo "already included"
							included=yes
							break
						fi
						echo -n "copying... "
						cp -Lp "$path/$lib" $BUILDROOT/image$PREFIX/lib/MonetDB/external/
						echo "included"
						included=yes
						break
					fi
				done
				[[ -z $included ]] && echo "not found"
			done
		else
			# Mach-O: grab and change install_names accordingly
			(
				$scantool -BRyF "%F:%n" $BUILDROOT/image | while read line ; do
					filename=${line%%:*}
					needed=${line#*:}
					for n in ${needed//,/ } ; do
						echo $filename:$n
					done
				done
			) > $BUILDROOT/needed.macho
			echo "including dependant libs into the image"

			scanandcopy() {
				local filename=${1##*/}
				local dir=${1%*/}
				local lib

				if [[ $dir == $PREFIX/* ]] ; then
					# file comes from the install image, abort now
					return 1
				fi

				if [[ -e $BUILDROOT/image$PREFIX/lib/MonetDB/external/$filename ]] ; then
					# file already exists in the image, silently skip,
					# but make sure the install_name is updated for the
					# lib requiring it
					return 0
				fi

				if [[ ! -e $1 ]] ; then
					# not existant? don't change it
					return 1
				fi

				if [[ $dir == /usr/lib* || $dir == /lib* ]] ; then
					# lib from the host? don't change it
					return 1
				fi

				# ok, copy it in
				echo -n "copying $filename... "
				cp -Lp "$1" $BUILDROOT/image$PREFIX/lib/MonetDB/external/
				chmod 644 $BUILDROOT/image$PREFIX/lib/MonetDB/external/$filename
				install_name_tool \
					-id $PREFIX/lib/MonetDB/external/$filename \
					$BUILDROOT/image$PREFIX/lib/MonetDB/external/$filename
				echo "included"

				# now recursively process the dependencies of the just
				# copied in lib
				(
					$scantool -ByF "%F:%n" "$BUILDROOT/image$PREFIX/lib/MonetDB/external/$filename" | while read line ; do
						local myneeded=${line#*:}
						for n in ${myneeded//,/ } ; do
							echo $n
						done
					done
				) > $BUILDROOT/needed.$filename

				for lib in $(<$BUILDROOT/needed.$filename) ; do
					scanandcopy $lib && \
					install_name_tool \
						-change "$lib" \
							"$PREFIX/lib/MonetDB/external/${lib##*/}" \
						"$BUILDROOT/image$PREFIX/lib/MonetDB/external/$filename"
				done

				rm $BUILDROOT/needed.$filename
				return 0
			}

			for lib in $(<$BUILDROOT/needed.macho) ; do
				filename=${lib%%:*}
				lib=${lib#*:}
				scanandcopy "${lib}" && \
				install_name_tool \
					-change "${lib}" "$PREFIX/lib/MonetDB/external/${lib##*/}" \
					"${filename}"
			done
		fi
	fi
	# finally make the tar
	tar --numeric-owner -jcf $PACKAGE \
		-C $BUILDROOT/image ${PREFIX#/}
}

src_compile() {
	local S=$BUILDROOT
	local A="MonetDB MonetDB-client"
	[[ -n $DO_JAVA ]] && A="$A MonetDB-java"
	[[ -n $DO_SQL ]] && A="$A MonetDB5-server MonetDB-SQL"
	[[ -n $DO_XQUERY ]] && A="$A MonetDB4-server MonetDB4-XQuery"
	[[ -n $DO_GEOM ]] && A="$A MonetDB-geom"
	[[ -n $DO_TEMPLATE ]] && A="$A MonetDB-template"
	[[ -n $DO_TESTING ]] && A="$A MonetDB-testing"

	local p
	local myconf

	# a wrapper configure script and makefile cannot be relied on yet
	for p in ${A} ; do
		cd "${S}"/$p/$(get_cvs_module $p) || die "cannot find directory $p"
		# work around bug I introduced due to my confusement...
		sed -i -e 's|MonetDB-clients/client|MonetDB-client/clients|g' configure
		chmod 755 configure
		econf \
			"--with-monetdb=included" \
			"--with-clients=included" \
			${DO_XQUERY+"--with-monetdb4=included"} \
			${DO_SQL+"--with-monetdb5=included"} \
			${DEBUG}
		emake || die "making $p failed"
	done
}

src_install() {
	local S=$BUILDROOT
	local A="MonetDB MonetDB-client"
	[[ -n $DO_JAVA ]] && A="$A MonetDB-java"
	[[ -n $DO_SQL ]] && A="$A MonetDB5-server MonetDB-SQL"
	[[ -n $DO_XQUERY ]] && A="$A MonetDB4-server MonetDB4-XQuery"
	[[ -n $DO_GEOM ]] && A="$A MonetDB-geom"
	[[ -n $DO_TEMPLATE ]] && A="MonetDB-template $A"
	[[ -n $DO_TESTING ]] && A="$A MonetDB-testing"

	local p

	for p in ${A} ; do
		cd "${S}"/$p/$(get_cvs_module $p) || die "cannot find directory $p"
		emake install || die "installing $p failed"
	done
}


echo "$(date)" > $LOG
echo "called with arguments: $ORGARG" >> $LOG
for a in $ACTION; do
	(((eval $a | tee -a $LOG) 3>&1 1>&2 2>&3 \
		| tee -a $LOG) 3>&1 1>&2 2>&3) \
		|| die "failed to execute $a"
done
echo "$(date)" >> $LOG

if [[ -n $PACKAGE ]] ; then
	echo "Created a binary package $PACKAGE"
	echo "You need to extract it in the root of the filesystem in order to be able to use it"
	exit 0
fi

echo "Successfully installed MonetDB in $PREFIX/bin"
case "${PREFIX%/}" in
	""|"/usr"|"/usr/local")
		;;
	*)
		cat << _EON

NOTE:
You installed MonetDB into a non-standard location.  Binaries, manpages
and Python modules will not be available by default, unless you:
- add $PREFIX/bin to your \$PATH,
- add $PREFIX/share/man to your \$MANPATH, and
- add $PREFIX/$(python -c 'import distutils.sysconfig; print distutils.sysconfig.get_python_lib(0,0,"")') to your \$PYTHONPATH.

_EON
		;;
esac
if [[ ${DO_SQL} == 1 ]] ; then
	cat << _EOS
You can start using MonetDB/SQL by running:
  $PREFIX/bin/merovingian

For further instructions to use merovingian, see:
  http://monetdb.cwi.nl/SQL/Documentation/Start-and-Stop.html
and read the merovingian(1), monetdb(1) and mclient(1) manpages to learn
how to create a database and afterwards connect to it.
_EOS
fi

