# Contributor: Valery Kartel <valery.kartel@gmail.com>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: Max Rees <maxcrees@me.com>

# Bundled libraries
#
# Name      | License | Location               | State
# ----------+---------+------------------------+---------
# bcmath    | LGPL2   | ext/bcmath/libbcmath   | used
# date      | MIT     | ext/date/lib           | used
# gd        | BSD     | ext/gd/libgd           | used
# file      | BSD     | ext/fileinfo/libmagic  | used
# libmbfl   | LGPLv2  | ext/mbstring/libmbfl   | used
# oniguruma | BSD     | ext/mbstring/oniguruma | used
# pcre      | BSD     | ext/pcre/pcrelib       | not used
# sqlite3   | Public  | ext/sqlite3/libsqlite  | not used
# libzip    | BSD     | ext/zip/lib            | not used
# libXMLRPC | BSD     | ext/xmlrpc/libxmlrpc   | used

# Static extensions
#
# Name      | Reason
# ----------+--------------------------------------------
# zlib      | https://bugs.alpinelinux.org/issues/8299

# secfixes:
#   7.2.16-r0:
#     - CVE-2016-10166
#     - CVE-2018-20783
#     - CVE-2019-6977
#     - CVE-2019-9020
#     - CVE-2019-9021
#     - CVE-2019-9022
#     - CVE-2019-9023
#     - CVE-2019-9024

pkgname=php7
_pkgname=php
pkgver=7.2.16
pkgrel=0
_apiver=20170718
pkgdesc="The PHP7 language runtime engine"
url="https://php.net/"
arch="all"
license="PHP-3.01 AND Zend-2.0 AND Custom:TSRM AND LGPL-2.1+ AND MIT AND Beerware AND Public-Domain AND BSD-3-Clause AND Apache-1.0 AND PostgreSQL AND BSD-2-Clause AND Zlib AND BSD-4-Clause"
depends=""
depends_dev="$pkgname=$pkgver-r$pkgrel autoconf icu-dev libedit-dev libxml2-dev
	pcre-dev zlib-dev"
makedepends="autoconf
	apache-httpd-dev
	aspell-dev
	bison
	bzip2-dev
	curl-dev
	db-dev
	enchant-dev
	freetds-dev
	freetype-dev
	gdbm-dev
	gettext-tiny
	gmp-dev
	icu-dev
	krb5-dev
	libedit-dev
	libical-dev
	libjpeg-turbo-dev
	libpng-dev
	openssl-dev
	libwebp-dev
	libxml2-dev
	libxpm-dev
	libxslt-dev
	libzip-dev
	net-snmp-dev
	openldap-dev
	pcre-dev
	postgresql-dev
	re2c
	sqlite-dev
	unixodbc-dev
	zlib-dev"
subpackages="$pkgname-dev $pkgname-doc $pkgname-apache $pkgname-phpdbg
	$pkgname-embed $pkgname-litespeed $pkgname-cgi $pkgname-fpm
	$pkgname-pear::noarch $pkgname-dbg"
source="http://php.net/distributions/$_pkgname-$pkgver.tar.bz2
	$_pkgname-fpm.initd
	$_pkgname-fpm.logrotate
	$_pkgname-module.conf
	disabled-tests.list
	install-pear.patch
	fpm-paths.patch
	allow-build-recode-and-imap-together.patch
	fix-tests-devserver.patch
	pwbuflen.patch
	enchant-2.patch"
builddir="$srcdir/$_pkgname-$pkgver"
_libdir="/usr/lib/$_pkgname"
_extension_dir="$_libdir/modules"
_extension_confd="/etc/$_pkgname/conf.d"

# Usage: add_ext [with|enable] name [extension dependencies...] [configure options...]
add_ext() {
	local ext="$1"
	shift
	# add_ext [with|enable] name -> --[with|enable]-name=shared
	if [ "$ext" = "with" ] || [ "$ext" = "enable" ]; then
		_configure_ext_opts="$_configure_ext_opts --$ext-$1=shared"
		ext="$1"
		shift
	fi

	case "$ext" in
		phar) subpackages="$subpackages $pkgname-$ext:$ext";;
		*) subpackages="$subpackages $pkgname-$ext:_extension";;
	esac
	_extensions="$_extensions $ext"

	local opt
	local prev
	for opt in $@; do
		case "$opt" in
		-*)
			# Add more configure options
			_configure_ext_opts="$_configure_ext_opts $opt"
			;;
		license:*)
			# Add custom license
			opt="$(printf '%s' "${opt#license:}" | sed 's/:/ AND /g')"
			eval "_licenses_$ext='$opt'"
			;;
		*)
			# Add dependencies
			prev="$(eval echo \$_deps_$ext)"
			eval "_deps_$ext='$prev $opt'"
			;;
	esac
	done
}
enable_ext() { add_ext enable $@; }
with_ext() { add_ext with $@; }

enable_ext 'bcmath' \
	license:LGPL-2.0+:PHP-3.01
with_ext 'bz2'
enable_ext 'calendar'
enable_ext 'ctype'
with_ext 'curl'
enable_ext 'dba' \
	--with-db4 \
	--with-dbmaker=shared \
	--with-gdbm
enable_ext 'dom'
with_ext 'enchant'
enable_ext 'exif' mbstring
enable_ext 'fileinfo' \
	license:PHP-3.0:BSD-2-Clause:BSD-3-Clause:Public-Domain
enable_ext 'ftp'
with_ext 'gd' \
	--with-freetype-dir=/usr \
	--disable-gd-jis-conv \
	--with-jpeg-dir=/usr \
	--with-png-dir=/usr \
	--with-webp-dir=/usr \
	--with-xpm-dir=/usr
with_ext 'gettext'
with_ext 'gmp'
with_ext 'iconv'
# Needs makedepeneds=imap-dev
#with_ext 'imap' \
#	--with-imap-ssl
enable_ext 'intl'
enable_ext 'json'
with_ext 'ldap' \
	--with-ldap-sasl
enable_ext 'mbstring' \
	license:PHP-3.01:OLDAP-2.8:BSD-2-Clause:Public-Domain:LGPL-2.0-only:LGPL-2.1-only
add_ext 'mysqli' mysqlnd openssl \
	--with-mysqli=shared,mysqlnd \
	--with-mysql-sock=/run/mysqld/mysqld.sock
enable_ext 'mysqlnd' openssl
add_ext 'odbc' \
	--with-unixODBC=shared,/usr
enable_ext 'opcache'
with_ext 'openssl' \
	--with-system-ciphers \
	--with-kerberos
enable_ext 'pcntl'
enable_ext 'pdo'
add_ext 'pdo_dblib' pdo \
	--with-pdo-dblib=shared
add_ext 'pdo_mysql' pdo mysqlnd \
	--with-pdo-mysql=shared,mysqlnd
add_ext 'pdo_odbc' pdo \
	license:PHP-3.0 \
	--with-pdo-odbc=shared,unixODBC,/usr
add_ext 'pdo_pgsql' pdo \
	--with-pdo-pgsql=shared
add_ext 'pdo_sqlite' pdo \
	--with-pdo-sqlite=shared,/usr
with_ext 'pgsql'
enable_ext 'phar'
enable_ext 'posix'
with_ext 'pspell'
# Needs makedepends=recode-dev
#with_ext 'recode'
enable_ext 'session'
enable_ext 'shmop'
enable_ext 'simplexml'
with_ext 'snmp'
enable_ext 'soap' \
	license:PHP-3.01:PHP-2.02
# Needs makedepends=libsodium-dev
#with_ext 'sodium'
enable_ext 'sockets'
add_ext 'sqlite3' \
	--with-sqlite3=shared,/usr
enable_ext 'sysvmsg'
enable_ext 'sysvsem'
enable_ext 'sysvshm'
# Needs makedepends=tidyhtml-dev
#with_ext 'tidy'
enable_ext 'tokenizer'
enable_ext 'wddx' xml
enable_ext 'xml'
enable_ext 'xmlreader' dom
with_ext 'xmlrpc' xml
enable_ext 'xmlwriter'
with_ext 'xsl' dom
enable_ext 'zip' \
	--with-libzip=/usr

# secfixes:
#   7.2.5-r0:
#     - CVE-2018-5712
#   7.2.8-r0:
#     - CVE-2015-9253
#     - CVE-2018-12882
#   7.2.11-r2:
#     - CVE-2018-19935

prepare() {
	default_prepare
	update_config_sub

	local vapi=$(sed -n '/#define PHP_API_VERSION/{s/.* //;p}' main/php.h)
	if [ "$vapi" != "$_apiver" ]; then
		error "Upstreram API version is now $vapi. Expecting $_apiver"
		error "After updating _apiver, all 3rd-party extensions must be rebuilt."
		return 1
	fi

	# https://bugs.php.net/63362 - Not needed but installed headers.
	# Drop some Windows specific headers to avoid installation,
	# before build to ensure they are really not needed.
	rm -f TSRM/tsrm_win32.h \
		TSRM/tsrm_config.w32.h \
		Zend/zend_config.w32.h \
		ext/mysqlnd/config-win.h \
		ext/standard/winver.h \
		main/win32_internal_function_disabled.h \
		main/win95nt.h

	# Fix some bogus permissions.
	find . -name '*.[ch]' -exec chmod 644 {} +

	# XXX: Delete failing tests.
	sed -n '/^[^#]/p' "$srcdir/disabled-tests.list" | while read item; do
		rm $item
	done

	autoconf
}

# Notes:
# * gd-jis-conv breaks any non-latin font rendering (vakartel).
# * libxml cannot be build as shared.
# * Doesn't work with system-provided onigurama, some tests fail (invalid code
#   point); probably because bundled onigurama is version 5.x, but we have 6.x.
_build() {
	EXTENSION_DIR=$_extension_dir ./configure \
		--build=$CBUILD \
		--host=$CHOST \
		--prefix=/usr \
		--libdir=$_libdir \
		--datadir=/usr/share/$_pkgname \
		--sysconfdir=/etc/$_pkgname \
		--localstatedir=/var \
		--enable-debug \
		--with-layout=GNU \
		--with-pic \
		--enable-maintainer-zts \
		--with-pear=/usr/share/$_pkgname \
		--with-config-file-path=/etc/$_pkgname \
		--with-config-file-scan-dir=$_extension_confd \
		--disable-short-tags \
		--with-icu-dir=/usr \
		--with-libedit \
		--without-readline \
		--enable-libxml \
			--with-libxml-dir=/usr \
		--with-pcre-regex=/usr \
		--with-zlib \
			--with-zlib-dir=/usr \
		$_configure_ext_opts \
		$@

	make
}

build() {
	# phpdbg
	_build --enable-phpdbg \
		--enable-phpdbg-webhelper \
		--disable-cgi \
		--disable-cli

	# apache-httpd module
	_build --disable-phpdbg \
		--disable-cgi \
		--disable-cli \
		--with-apxs2
	mv libs/libphp7.so sapi/apache2handler/mod_php.so

	# cgi, cli, fpm, embed, litespeed
	_build --disable-phpdbg \
		--enable-fpm \
		--enable-embed \
		--with-litespeed
}

check() {
	# PHP is so stupid that it's not able to resolve dependencies
	# between extensions and load them in correct order, so we must
	# help it...
	# opcache is Zend extension, it's handled specially in Makefile
	local php_modules="$(_extensions_by_load_order \
		| grep -vx opcache \
		| xargs -n 1 printf "'$builddir/modules/%s.la' ")"
	sed -i "/^PHP_TEST_SHARED_EXTENSIONS/,/extension=/ \
		s|in \$(PHP_MODULES)\"*|in $php_modules|" Makefile

	NO_INTERACTION=1 REPORT_EXIT_STATUS=1 \
		SKIP_SLOW_TESTS=1 SKIP_ONLINE_TESTS=1 TEST_TIMEOUT=10 \
		TZ= LANG= LC_ALL= \
		make test

	echo 'NOTE: We have skipped quite a lot tests, see disabled-tests.list.'
}

package() {
	make -j1 INSTALL_ROOT="$pkgdir" install

	install -Dm644 php.ini-production "$pkgdir"/etc/$_pkgname/php.ini
	find "$pkgdir" -name '.*' | xargs rm -rf
	rmdir "$pkgdir"/var/run
}

dev() {
	default_dev
	cd "$pkgdir"

	_mv usr/bin/phpize "$subpkgdir"/usr/bin/
	_mv ./$_libdir/build "$subpkgdir"/$_libdir/
}

doc() {
	default_doc
	cd "$builddir"

	mkdir -p "$subpkgdir/usr/share/doc/$_pkgname"
	cp CODING_STANDARDS CREDITS EXTENSIONS INSTALL LICENSE NEWS \
		README* UPGRADING* \
		"$subpkgdir/usr/share/doc/$_pkgname/"
}

apache() {
	pkgdesc="PHP7 Module for apache-httpd"
	depends="$pkgname apache-httpd"

	install -D -m 755 "$builddir"/sapi/apache2handler/mod_php.so \
		"$subpkgdir"/usr/libexec/apache2/mod_php.so
	install -D -m 644 "$srcdir"/php-module.conf \
		"$subpkgdir"/etc/apache2/conf.d/php-module.conf
}

phpdbg() {
	pkgdesc="Interactive PHP7 debugger"
	#depends="$pkgname" ?

	install -Dm755 "$builddir"/sapi/phpdbg/phpdbg \
		"$subpkgdir"/usr/bin/phpdbg
}

embed() {
	pkgdesc="PHP7 Embedded Library"
	#depends="$pkgname" ?

	_mv "$pkgdir"/usr/lib/libphp*.so "$subpkgdir"/usr/lib/
}

litespeed() {
	pkgdesc="PHP7 LiteSpeed SAPI"
	#depends="$pkgname" ?

	mkdir -p "$subpkgdir"/usr/bin
	mv "$pkgdir"/usr/bin/lsphp "$subpkgdir"/usr/bin
}

cgi() {
	pkgdesc="PHP7 Common Gateway Interface"
	depends="$pkgname"

	_mv "$pkgdir"/usr/bin/php-cgi "$subpkgdir"/usr/bin/
}

fpm() {
	pkgdesc="PHP7 FastCGI Process Manager"
	depends="$pkgname"
	cd "$pkgdir"

	_mv var "$subpkgdir"/
	_mv usr/share/$_pkgname/fpm "$subpkgdir"/var/lib/$_pkgname/
	_mv usr/sbin "$subpkgdir"/usr/
	_mv etc/$_pkgname/php-fpm* "$subpkgdir"/etc/$_pkgname/

	local file; for file in php-fpm.conf php-fpm.d/www.conf; do
		mv "$subpkgdir"/etc/$_pkgname/$file.default \
			"$subpkgdir"/etc/$_pkgname/$file
	done

	install -D -m 755 "$srcdir"/$_pkgname-fpm.initd \
		"$subpkgdir"/etc/init.d/php-fpm

	install -D -m 644 "$srcdir"/$_pkgname-fpm.logrotate \
		"$subpkgdir"/etc/logrotate.d/php-fpm

	mkdir -p "$subpkgdir"/var/log/$_pkgname
}

pear() {
	pkgdesc="PHP7 Extension and Application Repository"
	depends="$pkgname $pkgname-xml"
	cd "$pkgdir"

	# pecl needs xml extension and since we build it as shared, it must be
	# explicitly declared to be loaded.
	sed -i 's/\$INCARG/& -d extension=xml.so/' usr/bin/pecl

	mkdir -p "$subpkgdir"/usr/bin
	local file; for file in pecl pear peardev; do
		mv usr/bin/$file "$subpkgdir"/usr/bin/$file
	done

	_mv etc/php/pear.conf "$subpkgdir"/etc/php/
	_mv usr/share "$subpkgdir"/usr/
}

phar() {
	_extension
	cd "$pkgdir"

	mkdir -p "$subpkgdir"/usr/bin
	mv usr/bin/phar.phar "$subpkgdir"/usr/bin/phar.phar

	rm usr/bin/phar
	ln -s phar.phar "$subpkgdir"/usr/bin/phar
}

_extension() {
	local ext="${subpkgname#$pkgname-}"
	local extdesc="$(head -n1 "$builddir"/ext/$ext/CREDITS 2>/dev/null ||:)"
	depends="$pkgname"
	local dep; for dep in $(eval echo \$_deps_$ext); do
		depends="$depends $pkgname-$dep"
	done
	pkgdesc="PHP7 extension: ${extdesc:-$ext}"
	if [ -n "$(eval echo \$_licenses_$ext)" ]; then
		license="$(eval echo \$_licenses_$ext)"
	fi

	local load_order=$(_extension_load_order "$ext")

	# extension prefix
	local prefix=
	[ "$ext" = "opcache" ] && prefix="zend_"

	_mv "$pkgdir"/$_extension_dir/$ext.so \
		"$subpkgdir"/$_extension_dir/

	mkdir -p "$subpkgdir"/$_extension_confd
	echo "${prefix}extension=$ext.so" \
		> "$subpkgdir"/$_extension_confd/$(printf %02d $load_order)_$ext.ini
}

# Prints a load order (0-based integer) for the given extension name. Extension
# with lower load order should be loaded before exts with higher load order.
# It's based on number of dependencies of the extension (with exception for
# "imap"), which is flawed, but simple and good enough for now.
_extension_load_order() {
	local ext="$1"
	local deps="$(eval echo \$_deps_$ext)"

	case "$ext" in
		# This must be loaded after recode, even though it does
		# not depend on it.
		imap) echo 1;;
		# depends=$pkgname
		phar) echo 1;;
		*) echo "$deps" | wc -w;;
	esac
}

# Prints $_extensions sorted by load order and name.
_extensions_by_load_order() {
	local deps list ext

	for ext in $_extensions; do
		list="$list $(_extension_load_order $ext);$ext"
	done
	printf '%s\n' $list | sort -t ';' -k 1 | sed -E 's/\d+;//'
}

_mv() {
	local dest; for dest; do true; done  # get last argument
	mkdir -p "$dest"
	mv $@
}

sha512sums="f97545905a3ec4bc1ce431e306bffb2d7b6357164ea035a6899ea1589d8df4e6617af3924fa1abcb5da428ad691967504c3f94187d4cae6f2ef285e963d07e3d  php-7.2.16.tar.bz2
23df4e779c809db3e3b8e5b0353b1aafaad2f3dc56f2d1cd45f9b0e3ad71b32e40700d6ebfe914b3c87e8e0b670d0dc862ded1e5c898adf160e33dea372e044f  php-fpm.initd
01d4ba3ef104ea378eb0e8cbb7bdee3fdf65e4bd6865eb3bc6c0dc4af31c2d52887abdf0150b5ef984b877860285a3b1af84b11ffebb5b8b722ea9faf83edfeb  php-fpm.logrotate
a7f9ba5e11652fd1cb9e756c3269269a95de083ecb5be936a85c7a09c1396db9088e0251c6a643c40235c0e776fce2a471e5c7f5a033b85c7d3b3110c2b39e48  php-module.conf
b1008eabc86fcff88336fe2961e3229c159c930a05d97359136c381c5c1cc572a33110308a3e5ef5e31c60327f76c9ef02b375cd2ea8ff9caa7deeddc216f4ce  disabled-tests.list
f1177cbf6b1f44402f421c3d317aab1a2a40d0b1209c11519c1158df337c8945f3a313d689c939768584f3e4edbe52e8bd6103fb6777462326a9d94e8ab1f505  install-pear.patch
a77dd3bdf9dc7a0f2c06ff3e7c425d062bbaa29902c17402ce98701dc99499be863ad543aa5e6a7d1c249702d6afb193398dd3199ae58e42b32b95d434fb1883  fpm-paths.patch
f8ecae241a90cbc3e98aa4deb3d5d35ef555f51380e29f4e182a8060dffeb84be74f030a14c6b452668471030d78964f52795ca74275db05543ccad20ef1f2cc  allow-build-recode-and-imap-together.patch
f8bb322e56df79dd9f391737fb8737945cc730b14c7dc2ae8688979c565a9b97f5f2a12c9fcd0d8124624a9d09bd10228147d9e999bb94909bbe249f0a50646c  fix-tests-devserver.patch
8e538063d872f6770a57cdb844226a771ccda3d387dd1f199bb08c274b94fbe12ec0ef6df75c32071f308cb8f4ab51b91b520c7c2ed687adf96d0d322788e463  pwbuflen.patch
03de56676449ddc1ba1fc9c4fee2b2ed620cd1a8ce52d288c91b42e081182871ade55c8dbbe1c8286bc4eadcd92d497a62ac7b689ea8d6b1bcb5eb25225595c4  enchant-2.patch"