#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild
# Packager Luciano (venerdi_12)
# http://www.mesa.nl/pub/mpage

NAME=mpage
VERSION=2.5.6
ARCH=${ARCH:-i486}
BUILD=1lu
SOURCE=http://www.mesa.nl/pub/mpage/$NAME-$VERSION.$EXT
CWD=`pwd`
EXT=tgz

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

if ["$TMP" = ""]; then
 TMP=/tmp/txz
fi

PKG=$TMP/package-$NAME

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="gzip -d"
elif ["$EXT" = "zip" ]; then
   TARCMD="gunzip -d"
fi

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 -fPIC"; SLKLDFLAGS="-L/usr/lib64"; LIBDIRSUFFIX="64"
fi

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

cd $TMP

$TARCMD $CWD/$NAME-$VERSION.$EXT

cd $NAME-$VERSION

make clean

chown -R root:root .

CFLAGS="$SLKCFLAGS" \
make

mkdir -p $PKG/usr/bin
cp mpage $PKG/usr/bin

mkdir -p $PKG/usr/lib/mpage
cp Encodings/* $PKG/usr/lib/mpage

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

mkdir -p $PKG/usr/man
cp mpage.1 $PKG/usr/man

( 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
)

chmod 755 $PKG/usr/bin/*
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $CWD
cp -a *.SlackBuild slack-desc $PKG/usr/doc/$NAME-$VERSION
chown -R root:root $PKG/usr/doc/$NAME-$VERSION
find $PKG/usr/man -type f -exec gzip -9 {} \;
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
fi