#!/bin/sh
#
# Heavily based on the Slackware 13.0 SlackBuild
# http://www.ollisalonen.com/btnx
# Packager neongen ( neongen at libero.it)
# http://www.slacky.it
# re-packed for 13.0 by Luci0
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp/txz
fi

NAME=btnx
VERSION=0.4.11
ARCH=${ARCH:-i486}
BUILD=3ng
PKG=$TMP/package-$NAME
SOURCE=http://www.ollisalonen.com/btnx/$NAME-$VERSION.tar.gz

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

if [ ! -d $TMP ]; then
  mkdir -p $TMP
fi
if [ ! -d $PKG ]; then
  mkdir -p $PKG
fi

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

if [ ! -e $NAME-$VERSION.tar.gz ]; then
echo "Downloading source"
wget -c $SOURCE
fi

cd $TMP

echo "Unpacking $NAME..."
tar -xzf $CWD/$NAME-$VERSION.tar.gz

for i in 2 3 4 5;do
mkdir -p $PKG/etc/rc.d/rc$i.d
ln -s /etc/rc.d/init.d/$NAME $PKG/etc/rc.d/rc$i.d/S49$NAME
done

for i in 0 1 6;do
mkdir -p $PKG/etc/rc.d/rc$i.d
ln -s /etc/rc.d/init.d/$NAME $PKG/etc/rc.d/rc$i.d/K49$NAME
done

cd $NAME-$VERSION

find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;

chown -R root:root .

CFLAGS="$SLKCFLAGS" \
init_scripts_path=/etc/rc.d/init.d \
./configure --prefix=/usr \
--build=$CHOST-slackware-linux

make
make install DESTDIR=$PKG

mkdir -p $PKG/usr/doc/$NAME-$VERSION
cp -a AUTHORS COPYING ChangeLog INSTALL README $PKG/usr/doc/$NAME-$VERSION

# mkdir -p $PKG/etc/udev/rules.d
# touch $PKG/etc/udev/rules.d/99-btnx.rules

chown root:root -R $PKG
chmod 644 $PKG/usr/doc/$NAME-$VERSION/*

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

cd $PKG
find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
ADD="btnx-config >= 0.4.9-i486-1ng" \
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/../$NAME-$VERSION-$ARCH-$BUILD.txz

if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP
fi
