#!/bin/sh
# Heavily based on the Slackware 12.0 SlackBuild
# http://www.slacky.it
# http://www.wavpack.com/index.html 

NAME=wavpack
VERSION=4.41.0
ARCH=${ARCH:-i486}
BUILD=${BUILD:-1bj}

CWD=`pwd`
TMP=${TMP:-/tmp/tgz}
PKG=$TMP/package-$NAME
rm -rf $PKG 
mkdir -p $PKG 

if [ $ARCH == "i486" ]; then
 SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ $ARCH == "athlon-xp" ]; then
 SLKCFLAGS="-O2 -march=athlon-xp -fomit-frame-pointer -pipe"
elif [ $ARCH == "pentium4" ]; then
 SLKCFLAGS="-O2 -march=pentium4 -fomit-frame-pointer -pipe"
elif [ $ARCH == "pentiumm" ]; then
 SLKCFLAGS="-O2 -march=pentium-m -fomit-frame-pointer -pipe"
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2"
fi

if [ "$ARCH" == "x86_64" ]; then
  LIBDIR=/usr/lib64
else
  LIBDIR=/usr/lib
fi

# unpack the sources and fix their permissions
tar -xvjf $CWD/$NAME-$VERSION.tar.bz2 -C $TMP|| exit 1
tar -xvzf $CWD/xmms-wavpack.tar.gz -C $TMP || exit 1
cd $TMP/$NAME-$VERSION
chown -R root:root .
chmod -R u+w,go+r-w,a-s .
echo ""
echo "Starting compilation :)"

# run configure script
CFLAGS="$SLKCFLAGS" CXXFLAGS="$SLKCFLAGS" \
./configure \
 --prefix=/usr \
 --disable-static \
 --libdir=$LIBDIR \
 --disable-debug \
 --program-prefix= \
 --program-suffix= \
 --build=$ARCH-slackware-linux || exit 1
 
make || exit 1

# redirect installation of the package
make install DESTDIR=$PKG || exit 1

# Gzip manual pages
if [ -d $PKG/usr/man ]; then
  gzip -9 $PKG/usr/man/man?/*
fi

# add pre-compiled plugins for xmms
if [ -x /usr/bin/xmms ]; then 
(cd $PKG/usr/lib; mkdir -p xmms/Input; 
cp -a $TMP/xmms-wavpack/*.so $PKG/usr/lib/xmms/Input )
fi

# strip binaries and libreries
find $PKG | xargs file | grep "ELF 32-bit LSB executable" \
	  | cut -f 1 -d : | xargs strip --strip-all 2> /dev/null
find $PKG | xargs file | grep "shared object" \
          | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null	  

# copy the docs
mkdir -p $PKG/usr/doc/$NAME-$VERSION
cp -a \
  AUTHORS ChangeLog license* NEWS README \
  $PKG/usr/doc/$NAME-$VERSION/

# copy the slack-desc
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/slack-desc > $PKG/usr/doc/$NAME-$VERSION/slack-desc
cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION/$NAME.SlackBuild
echo "/sbin/ldconfig" > $PKG/install/doinst.sh

# build the package
cd $PKG
chown -R root:root .
requiredbuilder -y -v -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.tgz

# clean up the extra stuff
if [ "$1" = "--cleanup" ]; then 
  rm -rf $TMP 
fi
