#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild


CWD=`pwd`
NAME=iriverter
VERSION=0.16
TARGET=i486
BUILD=4lu
ARCH=${ARCH:-i486}
EXT=tar.bz2
SOURCE=http://surfnet.dl.sourceforge.net/sourceforge/iriverter//$NAME-$VERSION.$EXT

if [ ! -e $NAME-$VERSION.$EXT ]; then
wget -c $SOURCE
fi

if [ "$TMP" = "" ]; then
  TMP=/tmp/txz
fi
PKG=$TMP/package-$NAME

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

if [ "$EXT" = "tar.gz" ]; then
   TARCMD="tar xvzf"
elif [ "$EXT" = "tgz" ]; then
   TARCMD="tar xvzf"
elif [ "$EXT" = "tar.bz2" ]; then
   TARCMD="tar xvjf"
elif ["$EXT" = "gz" ]; then
   TARCMD="gunzip"
elif ["$EXT" = "zip" ]; then
   TARCMD="gzip"
fi

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
if [ ! -d $PKG ]; then
  mkdir -p $PKG # place for the package to be built
fi

echo "+================+"
echo "| $NAME-$VERSION |"
echo "+================+"

cd $TMP
$TARCMD $CWD/$NAME-$VERSION.$EXT
cd $NAME-$VERSION
chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \

./configure \
--prefix=/usr \
--with-swt=$CWD/swt.jar

make

mkdir -p $PKG/usr/bin
make prefix=$PKG/usr install

chmod 755 $PKG/usr/bin/*

mkdir -p $PKG/usr/doc/$NAME-$VERSION

cp $CWD/swt.jar /$PKG/usr/share/iriverter/lib
cp $CWD/d2.profile /$PKG/usr/share/iriverter/profiles

( 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
)
sed -i "s|$CWD|/usr/share/iriverter/lib/|g" $PKG/usr/bin/$NAME
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
chown -R root.root $PKG/usr/doc/$NAME-$VERSION

cd $PKG
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.txz

if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/$NAME-$VERSION
  rm -rf $PKG
fi
