#!/bin/sh

# Set initial variables
PRGNAM=libmirage
VERSION=1.2.0
ARCH=${ARCH:-i486}
BUILD=1we

CWD=$(pwd)
TMP=${TMP:-/tmp}
PKG=$TMP/package-$PRGNAM

NUMJOBS=${NUMJOBS:--j4}

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

# Make build environment and extract sources
rm -rf $PKG
mkdir -p $TMP $PKG
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.?z* || exit 1
cd $PRGNAM-$VERSION || exit 1

# Set permissions
chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

# Configure
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --mandir=/usr/man \
  --infodir=/usr/info \
  --docdir=/usr/doc/$PRGNAM-$VERSION \
  --with-html-dir=/usr/doc/$PRGNAM-$VERSION \
  --build=$ARCH-slackware-linux

# Build and install
make $NUMJOBS || make || exit 1
make install DESTDIR=$PKG

# Strip binaries
find $PKG | xargs file | grep "executable"    | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
find $PKG | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null

# Add documentation
mv $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM $PKG/usr/doc/$PRGNAM-$VERSION/html
cp -a AUTHORS COPYING ChangeLog INSTALL NEWS README $PKG/usr/doc/$PRGNAM-$VERSION
find $PKG/usr/doc/$PRGNAM-$VERSION -type f -exec chmod 644 {} \;
cat $CWD/slack-desc > $PKG/usr/doc/$PRGNAM-$VERSION/slack-desc
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

# Make package
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cd $PKG
requiredbuilder -y -v -s $CWD $PKG
makepkg -l y -c n $CWD/$PRGNAM-$VERSION-$ARCH-$BUILD.tgz
