#!/bin/bash

BASE=/tmp
PREFIX=$BASE/mpone
ALT_PREFIX=$BASE/mptwo
DISTFILES_DIR=$BASE/mpdistfiles
PORTFILES_DIR=$BASE/mpdports
SOURCE_DIR=$BASE/mpbase

if [ -z "$1" ]; then
	REV="HEAD"
else
	REV="$1"
fi

ZLIB_REV=53368

if [ ! -d $SOURCE_DIR ]; then
	mkdir -p $SOURCE_DIR
	svn co -r $REV http://svn.macosforge.org/repository/macports/trunk/base $SOURCE_DIR || exit $?
else
	svn up -r $REV $SOURCE_DIR || exit $?
fi
if [ ! -d $PORTFILES_DIR ]; then
	mkdir -p $PORTFILES_DIR
	svn co -r $ZLIB_REV -N http://svn.macosforge.org/repository/macports/trunk/dports $PORTFILES_DIR || exit $?
	svn up -r $ZLIB_REV -N $PORTFILES_DIR/archivers || exit $?
	svn up -r $ZLIB_REV $PORTFILES_DIR/archivers/zlib || exit $?
fi
if [ ! -d $PREFIX/var/macports/distfiles ]; then
	mkdir -p $DISTFILES_DIR $PREFIX/var/macports
	ln -s $DISTFILES_DIR $PREFIX/var/macports/distfiles || exit $?
fi

export PATH="/bin:/sbin:/usr/bin:/usr/sbin"

export GREP_OPTIONS=""

cd $SOURCE_DIR

./configure \
--prefix=$PREFIX \
--with-tclpackage=$PREFIX/Library/Tcl \
--with-applications-dir=$PREFIX/Applications \
--with-frameworks-dir=$PREFIX/Library/Frameworks \
--enable-readline || exit $?

make || exit $?

make install || exit $?

make distclean || exit $?

sed s%^rsync://rsync.macports.org/release/ports/%file://$PORTFILES_DIR% < "$PREFIX/etc/macports/sources.conf" > "$PREFIX/etc/macports/sources.conf.tmp"
mv "$PREFIX/etc/macports/sources.conf.tmp" "$PREFIX/etc/macports/sources.conf"

mv "$PREFIX" "$ALT_PREFIX" || exit $?
ln -s "$ALT_PREFIX" "$PREFIX" || exit $?

"$PREFIX/bin/port" install zlib
"$PREFIX/bin/port" -d deactivate zlib

EXIT=0
if [ -d "$PREFIX" ]; then
	echo "Bug absent in base rev $REV: $PREFIX exists"
else
	echo "Bug present in base rev $REV: $PREFIX is gone"
	EXIT=1
fi

rm -rf "$PREFIX" "$ALT_PREFIX"

exit $EXIT

