#!/bin/sh

# Slackware build script for gnulib

# Written by B. Watson (yalhcru@gmail.com)

# Licensed under the WTFPL. See http://www.wtfpl.net/txt/copying/ for details.

# Heavily based on Debian's package:
# https://packages.debian.org/sid/gnulib

# According to the gnulib docs at http://www.gnu.org/software/gnulib/,
# this build shouldn't exist: "there is no distribution tarball;
# the idea is to copy files from Gnulib into your own source tree."
# However, Debian packages it, and some projects that use it expect it
# to be installed system-wide (notably, lbzip2 does this). For practical
# reasons, I'm going to package this. Hopefully this saves someone else
# some work in the future.

PRGNAM=gnulib
VERSION=${VERSION:-20140202}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

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

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-${VERSION/+/-}-stable
tar xvf $CWD/${PRGNAM}_$VERSION+stable.orig.tar.gz
cd $PRGNAM-${VERSION/+/-}-stable
chown -R root:root .
find -L . \
 \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

find . \( -name '.git*' -o -name '.cvs*' \) -print0 | xargs -0 rm -rf

# does the same as Debian's 02-shebang.patch
sed -i '1s,#!/usr/local/bin,#!/usr/bin,' lib/uniname/gen-uninames.lisp

make -C doc info
make -C doc html

# Debian does this, is it really necessary?
chmod 755 tests/*.in.sh lib/config.charset

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild
mv doc/*html COPYING ChangeLog DEPENDENCIES README NEWS* users.txt STATUS* \
  $PKG/usr/doc/$PRGNAM-$VERSION

mkdir -p $PKG/usr/info
gzip -9c < doc/$PRGNAM.info > $PKG/usr/info/$PRGNAM.info.gz
rm -f doc/$PRGNAM.info

mkdir -p $PKG/usr/share/$PRGNAM
cp -a * $PKG/usr/share/$PRGNAM

mkdir -p $PKG/usr/bin
ln -s ../share/$PRGNAM/check-module $PKG/usr/bin/check-module
ln -s ../share/$PRGNAM/gnulib-tool $PKG/usr/bin/gnulib-tool

# man pages lifted straight from the Debian package
mkdir -p $PKG/usr/man/man1
for i in $CWD/manpages/*.1; do
  gzip -9c < $i > $PKG/usr/man/man1/$( basename $i ).gz
done

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.${PKGTYPE:-tgz}
