#!/bin/sh
# Set initial variables:
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-apr-util

VERSION=1.3.4
ARCH=${ARCH:-x86_64}
BUILD=${BUILD:-1}
DISTRO=${DISTRO:-slamd64}

if [ $DISTRO = slackware ]; then
	PKGARCH=$ARCH
else
	PKGARCH=${ARCH}_${DISTRO}
fi

if [ $DISTRO = slamd64 ]; then
	LIBSUFFIX=${LIBSUFFIX:-64}
else
	LIBSUFFIX=${LIBSUFFIX:-}
fi

if [ "x$LIBSUFFIX" = "x64" -a -e /var/log/packages/expat32* ]; then
	echo "This package won't build in 64-bits mode while expat32 is installed."
	exit 1
fi

if [ "$ARCH" = "i386" ]; then
  SLKCFLAGS="-O2 -march=i386 -mcpu=i686"
elif [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "s390" ]; then
  SLKCFLAGS="-O2"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
rm -rf $PKG
mkdir -p $PKG

cd $TMP
rm -rf apr-util-$VERSION
tar xjvf $CWD/apr-util-$VERSION.tar.bz2
cd apr-util-$VERSION

# For now, this isn't working with svn (here, anyway) and is probably
# more trouble than it's worth.  Could be a grey area in regards to
# licensing, too -- the Apache people say it's fine for third parties
# to link this and distribute the result, but there are usually some
# differing opinions when it comes to this sort of thing...
#( cd dbd ; lftpget http://apache.webthing.com/svn/apache/apr/apr_dbd_mysql.c )
#  --with-mysql=/usr \
#

chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

CFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --libdir=/usr/lib$LIBSUFFIX \
  --with-apr=/usr \
  --with-dbm=db44 \
  --with-berkeley-db \
  --without-gdbm \
  --with-ldap \
  --disable-static \
  --without-sqlite2 \
  $ARCH-$DISTRO-linux

make -j15 || make || exit 1
make dox || exit 1
make install DESTDIR=$PKG

( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

mkdir -p $PKG/usr/doc/apr-util-$VERSION
cp -a \
  CHANGES INSTALL.MySQL LICENSE NOTICE \
  $PKG/usr/doc/apr-util-$VERSION

# This just seems like way too much stuff...
#mv docs/dox/html $PKG/usr/doc/apr-util-$VERSION

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

# Build the package:
cd $PKG
makepkg -l y -c n $TMP/apr-util-$VERSION-$PKGARCH-$BUILD.tgz

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/apr-util-$VERSION
  rm -rf $PKG
fi