#!/bin/bash

# Slackware build script for php-ext-xz

# Written by B. Watson (urchlay@slackware.uk)

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

# Note: This is the first PHP extension I've ever packaged. I did a
# few things differently from how other PHP extensions might be done.

# - The xz.ini file defaults to enabling the extension. This means
#   you don't have to edit the config file after installing the
#   package. I did this by analogy with perl and python modules:
#   there's no config file to edit when you install one of those.
#   I *did* still make it a .new file, so if the admin comments it out,
#   it'll stay that way.

# - I didn't pass a ton of template arguments to ./configure. None are
#   needed, because configure calls php-config (which it finds in
#   /usr/bin without help) and sets the correct install directories.

# - This isn't PHP-specific, but I use LDFLAGS="-Wl,-s" to have it
#   strip the .so library at build time, rather than a separate
#   strip command after 'make install'. I would have used "make
#   install-strip" but this project doesn't support it.

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=php-ext-xz
VERSION=${VERSION:-1.2.2}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

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

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

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

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-$VERSION.tar.gz --no-same-owner
cd $PRGNAM-$VERSION
find . ! -type l    -a \( \
  \(     -perm /111 -a ! -perm 755 -a -exec chmod -f 755 {} + \) -o \
  \(   ! -perm /111 -a ! -perm 644 -a -exec chmod -f 644 {} + \) \)

# Note: doesn't use DESTDIR (though, some other PHP extensions do).
# Also, install-strip not supported.
phpize
LDFLAGS="-Wl,-s" CFLAGS="$SLKCFLAGS" ./configure
make
make install INSTALL_ROOT=$PKG

mkdir -p $PKG/etc/php.d/
cat <<EOF > $PKG/etc/php.d/xz.ini.new
; xz.ini, part of SlackBuilds.org's libraries/php-ext-xz.
; Comment out the next line to disable the extension:
extension=xz
EOF

PKGDOC=$PKG/usr/doc/$PRGNAM-$VERSION
mkdir -p $PKGDOC
cp -a README* LICENSE* $PKGDOC
cat $CWD/$PRGNAM.SlackBuild > $PKGDOC/$PRGNAM.SlackBuild

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
