#!/bin/sh
# Heavily based on the Slackware 13.0 SlackBuild
# prozilla.SlackBuild created by danix
# re-packed for 13.0 by Lucio

set -e

# Setting up initial variables:
APP=prozilla
VERSION=2.0.4
ARCH=${ARCH:-i486}
BUILD=4dx
CWD=$(pwd)
TMP=${TMP:-/tmp/$APP}
PKG=$TMP/package-$APP

# Setting up SLKCFLAGS
if [ "$ARCH" = "i386" ]; then
	SLKCFLAGS="-O2 -march=i386 -mtune=i686"
elif [ "$ARCH" = "i486" ]; then
	SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "x86-64" ]; then
	SLKCFLAGS="-O2 -fPIC"
fi

# Extracting Sources
if [ ! -d $TMP ]; then
    mkdir -p $TMP
else
    rm -rf $TMP/*
fi
if [ ! -d $PKG ]; then
    mkdir -p $PKG
else
    rm -rf $PKG/*
fi
cd $TMP
tar -jxvf "$CWD"/$APP-$VERSION.tar.bz2
cd $APP-$VERSION
zcat $CWD/extra-qualification.diff.gz | patch -p1 -E --backup --verbose
chown -R root:root .
chmod -R u+w,go+r-w,a-s .

# Configure and compile sources
CFLAGS="$SLKCFLAGS" \
	./configure \
	--prefix=/usr \
	--sysconfdir=/etc \
	--localstatedir=/var \
	--build=$ARCH-slackware-linux \
	--host=$ARCH-slackware-linux
make
make install DESTDIR=$PKG

# Install documentation
mkdir -p $PKG/usr/doc/$APP-$VERSION
cp -a CREDITS COPYING ChangeLog README TODO docs/ /$PKG/usr/doc/$APP-$VERSION
find /$PKG/usr/doc/$APP-$VERSION -type f -exec chmod 644 {} \;
cat "$CWD"/$APP.SlackBuild > $PKG/usr/doc/$APP-$VERSION/$APP.SlackBuild

# Final tuning
mkdir -p $PKG/install
cat "$CWD"/slack-desc > $PKG/install/slack-desc
if [ -e "$CWD"/doinst.sh.gz ]; then
	zcat "$CWD"/doinst.sh.gz > $PKG/install/doinst.sh
fi
(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 objects" | grep ELF | cut -f 1 -d : | xargs strip --strip unneeded 2> /dev/null
)
if [ -d $PKG/usr/man ]; then
	(cd $PKG/usr/man
	find . -type f -exec gzip -9 {} \;
	for i in `find . -type l` ; do ln -s $( readlink $i ).gz $i.gz; rm $i; done
	)
fi
if [ -d $PKG/usr/info ]; then
	gzip -9 $PKG/usr/info/*.info
	rm -f $PKG/usr/info/dir
fi

# Building the package
cd $PKG
# Il seguente comando cancella un file vuoto che genererebbe
# un WARNING di makepkg.
rm usr/doc/prozilla-2.0.4/docs/Makefile
requiredbuilder -v -y -s $CWD $PKG
/sbin/makepkg -l y -c n "$CWD"/../$APP-$VERSION-$ARCH-$BUILD.txz

if [ "$1" ]; then
    if [ "$1" = "--cleanup" ]; then
	rm -rf $TMP
	rm -rf $PKG
    else
	echo "$0: unrecognized option \`$1'"
    fi
fi
