#!/bin/sh
# Heavily based on the Slackware 12.0 SlackBuild
# http://www.swi-prolog.org/
# Packager Alessio Di Fazio a.k.a. Slux <slux83@gmail.com>

CWD=`pwd`
TMP=${TMP:-/tmp/tgz}
PKG=$TMP/package-pl
NAME=pl
VERSION=5.6.54
ARCH=${ARCH:-i486}
BUILD=1slx
PREFIX=/usr

# CFLAGS
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="-O3 -march=i686 -pipe"
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

cd $TMP

tar xfvz $CWD/$NAME-$VERSION.tar.gz  || exit 1

cd $NAME-$VERSION

chown -R root:root .

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

CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
--prefix=$PREFIX \
--with-world \
--without-jpl \
--enable-gmp \
--disable-debug \
--program-prefix= \
--program-suffix= \
--build=$ARCH-slackware-linux || exit 1

#make or exit on error
make || exit 1

#make install with DESTDIR ## note: this comment is pretty useless :-=
make install DESTDIR=$PKG

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

cp -a ANNOUNCE COPYING ChangeLog INSTALL INSTALL.notes README VERSION $PKG/usr/doc/$NAME-$VERSION
find $PKG/usr/doc/$NAME-$VERSION -type f -exec chmod 644 {} \;

( 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
  find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs strip -g 2> /dev/null
)

# Compress man pages if they exist
if [ -d $PKG/usr/man ]; then
   gzip -9 $PKG/usr/man/*/*
fi

# Compress info pages if they exist (and remove the dir file)
if [ -d $PKG/usr/info ]; then
   gzip -9 $PKG/usr/info/*.info
   rm -f $PKG/usr/info/dir
fi

#Create the ./install directory and copy the slack-desc into it
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

# Build the package
cd $PKG
requiredbuilder -v -y -s $CWD $PKG
makepkg -l y -c n $CWD/$NAME-$VERSION-$ARCH-$BUILD.tgz

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