#!/bin/bash

# php.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>

# Record toolchain & other info for the build log:
slackbuildinfo

# Paths to skeleton port's source & real Slackware source tree:
export CWD=$SLACKSOURCE/$PKGNAM
export PORTCWD=$PWD

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# Determine the CFLAGS for the known architectures:
case $ARCH in
   arm)     export SLKCFLAGS="-O2 -march=armv5te"
            ### export SLKCONFARGS="--with-sqlite3=shared,/usr"
            export LIBDIRSUFFIX="" ;;
   *)       export SLKCFLAGS="-O2" ;;
esac

############# Extract ALPINE ######################################
# We extract the ALPINE c-client source built previously
# 
IMAPLIBDIR=/usr/local/lib/c-client
rm -rf $IMAPLIBDIR

# Where are the alpine IMAP headers?
# The location differs depending on whether we're building in /patches
# or /source:
echo $PORTCWD | grep -q /patches/ && ALPINEHDRLOC=$PORTCWD/../../../source/n/alpine/sources/ || ALPINEHDRLOC=$PORTCWD/../alpine/sources/

if [ ! -s $ALPINEHDRLOC/alpine-headers.tar.*z* ]; then
   echo "*** NO ALPINE SOURCE AVAILABLE ***"
   echo "*** Run ../alpine/alpine.SlackBuild first ***"
   failmake
fi

( cd $TMPBUILD
  tar xf $ALPINEHDRLOC/alpine-headers.tar.*z*
  cd alpine-headers || exit 1
  strip -g c-client.a
  mkdir -vpm755 $IMAPLIBDIR/{lib,include}
  cp -Lfv c-client.a $IMAPLIBDIR/lib
  cp -Lfv *.h $IMAPLIBDIR/include )

################################################################

# Generic "kitchen sink" configure function, with as many things as possible (and
# maybe then some ;-) compiled as shared extensions:
php_configure() {
LDADD="-ldl -lpthread" \
LIBS="-ldl -lpthread" \
LDFLAGS="-ldl -lpthread" \
EXTENSION_DIR=/usr/lib/php/extensions \
CFLAGS="$SLKCFLAGS $LDADD" \
./configure --prefix=/usr \
  $* \
   --prefix=/usr \
   --libdir=/usr/lib${LIBDIRSUFFIX} \
   --with-libdir=lib${LIBDIRSUFFIX} \
   --localstatedir=/var \
   --sysconfdir=/etc \
   --datarootdir=/usr/share \
   --datadir=/usr/share \
   --infodir=/usr/info \
   --mandir=/usr/man \
   --with-apxs2=/usr/bin/apxs \
   --enable-fpm \
   --with-fpm-user=apache \
   --with-fpm-group=apache \
   --enable-maintainer-zts \
   --enable-pcntl \
   --enable-mbregex \
   --enable-tokenizer=shared \
   --with-config-file-scan-dir=/etc/php \
   --with-config-file-path=/etc/httpd \
   --enable-mod_charset \
   --with-layout=PHP \
   --disable-sigchild \
   --enable-xml \
   --with-libxml-dir=/usr \
   --enable-simplexml \
   --enable-xmlreader=shared \
   --enable-dom=shared \
   --enable-filter \
   --disable-debug \
   --with-openssl=shared \
   --with-pcre-regex=/usr \
   --with-zlib=shared,/usr \
   --enable-bcmath=shared \
   --with-bz2=shared,/usr \
   --enable-calendar=shared \
   --enable-ctype=shared \
   --with-curl=shared \
   --with-curlwrappers \
   --with-mcrypt=/usr \
   --enable-dba=shared \
   --with-gdbm=/usr \
   --with-db4=/usr \
   --enable-exif=shared \
   --enable-ftp=shared \
   --with-gd=shared \
   --with-jpeg-dir=/usr \
   --with-png-dir=/usr \
   --with-zlib-dir=/usr \
   --with-xpm-dir=/usr \
   --with-freetype-dir=/usr \
   --with-t1lib=/usr \
   --enable-gd-native-ttf \
   --with-gettext=shared,/usr \
   --with-gmp=shared,/usr \
   --with-iconv=shared \
   --with-imap-ssl=/usr \
   --with-imap=$IMAPLIBDIR \
   --with-ldap=shared \
   --enable-mbstring=shared \
   --enable-hash \
   --with-mysql=shared,mysqlnd \
   --with-mysqli=shared,mysqlnd \
   --with-mysql-sock=/var/run/mysql/mysql.sock \
   --enable-pdo=shared \
   --with-pdo-mysql=shared,mysqlnd \
   --with-pdo-sqlite=shared,/usr \
   --with-pspell=shared,/usr \
   --with-enchant=shared,/usr \
   --enable-shmop=shared \
   --with-snmp=shared,/usr \
   --enable-soap=shared \
   --enable-sockets \
   --with-sqlite3=shared \
   --with-regex=php \
   --enable-sysvmsg \
   --enable-sysvsem \
   --enable-sysvshm \
   --enable-wddx=shared \
   --with-xsl=shared,/usr \
   --enable-zip=shared \
   --enable-shared=yes \
   --enable-static=no \
   --with-gnu-ld \
   --with-pic \
   --with-tsrm-pthreads \
   --enable-intl=shared \
   --build=$ARCH-slackware-linux-gnueabi || exit 1
}

# Function to extract source:
# On ARM, with PHP4 I found that I had to begin from scratch for every 
# build of php.  With php5 I don't know but I'm sure it's just fine to
# continue with this trend of starting afresh -- it just takes longer.
function extract_php_source() {
  cd $TMPBUILD
  # Extract PHP source:
  rm -rf php-*
  tar xvvf $CWD/$PKGNAM-$VERSION.tar.?z* || exit 1

  cd $PKGNAM-$VERSION
  slackhousekeeping
  find . -name "*.orig" -print0 | xargs -0 rm -f
  find . -name "*.h" -exec chmod 644 {} \;

  # Sometimes they ship a few of these:
  find . -name "*.orig" -exec rm {} \;

  # Add missing(?) PEAR modules back:
  if [ -d php-$VERSION/pear/packages ]; then
    ( cd php-$VERSION/pear/packages
      cp -a $CWD/pear/*.bz2 . 2> /dev/null
      bzip2 -d *.bz2 2> /dev/null
    )
  fi

  # Add install-pear-nozlib.phar if it wasn't shipped in the PHP tarball:
  if [ ! -r pear/install-pear-nozlib.phar ]; then
    xzcat $CWD/install-pear-nozlib.phar.xz > pear/install-pear-nozlib.phar || exit 1
  elif [ -r $CWD/install-pear-nozlib.phar.xz ]; then
    echo "pear/install-pear-nozlib.phar found in the PHP tarball...  recommend removing possibly stale version in \$CWD."
    echo "Have a little time to think this over..."
    sleep 3600
  fi

  # Patch ini files:
   zcat $CWD/php.ini-development.diff.gz | patch -p1 --verbose || exit 1
   zcat $CWD/php.ini-development.diff.gz | patch -p1 --verbose php.ini-production || exit 1
   zcat $CWD/php-fpm.conf.diff.gz | patch -p1 --verbose || exit 1

   # Install the build folder into /usr/lib$LIBDIRSUFFIX/php/build
   # and adapt phpize accordingly:
   sed -i "s|build$|php/build|" scripts/Makefile.frag
   sed -i "s|build\"$|php/build\"|" scripts/phpize.in

  # Apply patches. These come from Debian's diff:
  if [ $ARCH = arm ]; then

     # Unpack the patch set:
     tar xf $PORTCWD/sources/php*debian* || exit 1

    for pf in \
       033-we_WANT_libtool.patch \
       044-strtod_arm_fix.patch ; do
      auto_apply_patch debian/patches/$pf || exit 1
    done

#     # PHP ships with libtool 1.4.3, which is buggy on ARM, so we force it to
#     # rebuild the configure system with the native autoconf tools
#     # Force the rebuild of the libtool components:
#     rm -f aclocal.m4 config.sub config.guess ltmain.sh
#     #libtoolize --force # we used to need this for older versions of php but
#     # now the Debian patch applied above forces it anyway.
     ./buildconf --force

  fi
}

##################################################################
mkdir -p $PKG/etc/httpd
mkdir -p $PKG/etc/php
# A trick from DaMouse to enable building php into $PKG.
# We'll remove this later on.
cat /etc/httpd/original/httpd.conf > $PKG/etc/httpd/httpd.conf
if [ ! -e /etc/httpd/original/httpd.conf ]; then
  echo "FATAL:  no /etc/httpd/original/httpd.conf found."
  exit 1
fi
##################################################################

################## Build Apache module & CGI interpreter ################

# Extract the PHP source archive:
extract_php_source

echo ":::::Building Apache2 module:::::"
# Make the Apache2 module version of PHP:
php_configure || exit 1
make $NUMJOBS LDFLAGS="-lpthread -ldl" || failmake
make install INSTALL_ROOT=$PKG || failinstall

mkdir -vpm755 $PKG/etc/{rc.d,php-fpm}
install -vpm644 sapi/fpm/init.d.php-fpm $PKG/etc/rc.d/rc.php-fpm.new

################### Clean up the installation ###################

# PHP (used to) install Pear with some strange permissions.
chmod 755 $PKG/usr/bin/pear

# PHP sometimes puts junk in the root directory:
( cd $PKG
  rm -rvf .channels .depdb .depdblock .filemap .lock .registry
)

# We do not package static extension libraries:
rm -f $PKG/usr/lib${LIBDIRSUFFIX}/php/extensions/*.a

# Fix $PKG/usr/lib/php perms:
( cd $PKG/usr/lib${LIBDIRSUFFIX}/php
  find . \
   \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
   -exec chmod 755 {} \; -o \
   \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
   -exec chmod 644 {} \;
)

# Copy docs:
mkdir -pm755 $PKG/usr/doc/php-$VERSION
cp -a \
  CODING_STANDARDS CREDITS EXTENSIONS INSTALL LICENSE NEWS README* TODO* UPGRADING* \
  sapi/cgi/README.FastCGI \
  $PKG/usr/doc/php-$VERSION

mkdir -pm755 $PKG/etc/httpd
cp -a php.ini-development php.ini-production $PKG/etc/httpd
cp -a $CWD/mod_php.conf.example $PKG/etc/httpd
chmod 644 $PKG/etc/httpd/*
chown root:root $PKG/etc/httpd/*

# This can go now.
rm -f $PKG/etc/httpd/httpd*

# These are misplaced:
mkdir -pm755 $PKG/usr/man/man1
mv -f $PKG/usr/php/man/man1/* $PKG/usr/man/man1/
rmdir $PKG/usr/php

# If necessary, start the fakeroot server so we can set file/dir ownerships:
start_fakeroot

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
slackgzpages -i # compress man & info pages and delete usr/info/dir
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs

# Session directory for PHP - needs special permissions, therefore
# goes after the 'slackslack' call.
mkdir -pm770 $PKG/var/lib/php
chown root:apache $PKG/var/lib/php

slackdesc       # install slack-desc and doinst.sh
slackmp         # run makepkg -l y -c n

# Perform any final checks on the package:
cd $PKG
slackhlinks     # search for any hard links
