#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

# This has to be exported to make some magic below work.
export DH_OPTIONS

# Hardcode correct absolute path to sed
export ac_cv_path_SED = $(shell command -v sed)

SANE_ARCHS := amd64 i386 arm64

# Enable parallel builds
PARALLEL=--parallel

# Enable this for debugging the sed scripts
#SED=$(CURDIR)/debian/sedsed
export SED := /bin/sed

# Make the shell scripts fail after first failed command (important for SAPI loops)
SHELL := /bin/sh -e

# enable dpkg build flags
export DEB_BUILD_MAINT_OPTIONS = hardening=+all optimize=-lto
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/default.mk

export DEB_HOST_MULTIARCH
PHP_SOURCE_VERSION   := $(DEB_VERSION)
PHP_UPSTREAM_VERSION := $(DEB_VERSION_UPSTREAM)
PHP_DEBIAN_REVISION  := $(shell echo $(PHP_SOURCE_VERSION) | $(SED) -e 's/.*-//')
PHP_DFSG_VERSION     := $(shell echo $(PHP_UPSTREAM_VERSION) | $(SED) -e 's/+.*//')
PHP_MAJOR_VERSION    := $(shell echo $(PHP_DFSG_VERSION) | awk -F. '{print $$1}')
PHP_MINOR_VERSION    := $(shell echo $(PHP_DFSG_VERSION) | awk -F. '{print $$2}')
PHP_RELEASE_VERSION  := $(shell echo $(PHP_DFSG_VERSION) | awk -F. '{print $$3}')

# Enable ZTS build if $(DEB_SOURCE) ends with -zts
ZTS=$(shell echo $(DEB_SOURCE) | sed 's/php$(PHP_MAJOR_VERSION).$(PHP_MINOR_VERSION)//')
ifeq ($(ZTS),-zts)
$(warning Enabling ZTS build)
CONFIGURE_ZTS        := --enable-maintainer-zts
endif

PHP_NAME_VERSION     := $(PHP_MAJOR_VERSION).$(PHP_MINOR_VERSION)$(ZTS)
PHP_ZEND_VERSION     := $(shell $(SED) -ne 's/\#define ZEND_MODULE_API_NO //p' Zend/zend_modules.h)$(ZTS)

ifneq ($(DEB_SOURCE),php$(PHP_NAME_VERSION))
$(error $(DEB_SOURCE) != php$(PHP_NAME_VERSION))
endif
REAL_TARGETS         := apache2 phpdbg embed fpm cgi cli
EXTRA_TARGETS        := ext
TARGETS              := $(EXTRA_TARGETS) $(REAL_TARGETS)

# Special package names
PHP_PHP      := php$(PHP_NAME_VERSION)
PHP_COMMON   := php$(PHP_NAME_VERSION)-common
PHP_FPM      := php$(PHP_NAME_VERSION)-fpm
PHP_LIBEMBED := libphp$(PHP_NAME_VERSION)-embed
PHP_DEV      := php$(PHP_NAME_VERSION)-dev
PHP_APACHE2  := libapache2-mod-php$(PHP_NAME_VERSION)
PHP_CGI      := php$(PHP_NAME_VERSION)-cgi
PHP_CLI      := php$(PHP_NAME_VERSION)-cli
PHP_PHPDBG   := php$(PHP_NAME_VERSION)-phpdbg

# Generic commands

SED_VARIABLES := \
	$(SED) -e "s,@sapi@,$${sapi},g"				|\
	$(SED) -e "s,@package@,$${package},g"			|\
	$(SED) -e "s,@extensions@,$${extensions},g"		|\
	$(SED) -e "s,@module@,$${module},g"			|\
	$(SED) -e "s,@extdir@,$${extdir},g"			|\
	$(SED) -e "s,@priority@,$${priority},g"			|\
	$(SED) -e "s,@PHP_VERSION@,$(PHP_NAME_VERSION),g"	|\
	$(SED) -e "s,@PHP_MAJOR@,$(PHP_MAJOR_VERSION),g"	|\
	$(SED) -e "s,@PHP_MINOR@,$(PHP_MINOR_VERSION),g"	|\
	$(SED) -e "s,@PHP_RELEASE@,$(PHP_RELEASE_VERSION),g"	|\
	$(SED) -e "s,@PHP_API@,$(PHP_ZEND_VERSION),g"

SED_REPLACEMENT := $(SED) -e "/\#EXTRA\#/ r debian/$${versionless}.$${tmpl}.extra" | $(SED_VARIABLES) | $(SED) -e '/\#EXTRA\#/ d'

SAPI_PACKAGE := \
	case $${sapi} in \
	  embed)         package=$(PHP_LIBEMBED); source=libphp-$${sapi} ;; \
	  apache2)       package=$(PHP_APACHE2); source=libapache2-mod-php ;; \
	  *)             package=php$(PHP_NAME_VERSION)-$${sapi}; source=php-$${sapi} ;; \
	esac; \
	versionless=$$(echo $${package} | $(SED) -e 's/$(PHP_NAME_VERSION)//g');

MODULE_PACKAGE := \
	package=php$(PHP_NAME_VERSION)-$${module}; \
	versionless=$$(echo $${package} | $(SED) -e 's/$(PHP_NAME_VERSION)//g');

LIBTOOL_VERSION := $(shell dpkg-query -f'$${Version}' -W libtool)

# Disable the test now
RUN_TESTS := yes
ifeq (nocheck,$(filter nocheck,$(DEB_BUILD_PROFILES)))
  $(warning Disabling tests due DEB_BUILD_PROFILES)
  DEB_BUILD_OPTIONS += nocheck
  RUN_TESTS := no
else
  ifeq (nocheck,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
    $(warning Disabling tests due DEB_BUILD_OPTIONS)
    RUN_TESTS := no
  endif
endif
ifeq (,$(filter $(DEB_HOST_ARCH),$(SANE_ARCHS)))
  $(warning Disabling checks on $(DEB_HOST_ARCH))
  RUN_TESTS := no
endif

CONFIGURE_PCRE_JIT :=
ifeq (,$(filter $(DEB_HOST_ARCH),$(SANE_ARCHS)))
  CONFIGURE_PCRE_JIT := --without-pcre-jit
endif

ifeq ($(DEB_HOST_ARCH),$(filter $(DEB_HOST_ARCH),amd64 armel armhf i386 ia64 powerpc))
  CONFIGURE_DTRACE_ARGS := --enable-dtrace
else
  CONFIGURE_DTRACE_ARGS := --disable-dtrace
endif

ifeq ($(DEB_HOST_ARCH_OS),linux)
  CONFIGURE_SYSTEMD := --with-fpm-systemd
  CONFIGURE_APPARMOR := --with-fpm-apparmor
endif

# specify some options to our patch system
QUILT_DIFF_OPTS := -p
QUILT_NO_DIFF_TIMESTAMPS := 1
export QUILT_DIFF_OPTS QUILT_NO_DIFF_TIMESTAMPS

export PROG_SENDMAIL := /usr/sbin/sendmail
ifeq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
  DEB_CFLAGS_MAINT_APPEND += -O2
else
  DEB_CFLAGS_MAINT_APPEND += -O0
endif
DEB_CFLAGS_MAINT_APPEND += -Wall -pedantic -fsigned-char -fno-strict-aliasing 
DEB_CFLAGS_MAINT_APPEND += $(shell getconf LFS_CFLAGS)

# OpenSSL 3.0 support
DEB_CFLAGS_MAINT_APPEND += -DOPENSSL_SUPPRESS_DEPRECATED

# Enable IEEE-conformant floating point math on alphas (not the default)
ifeq (alpha-linux-gnu,$(DEB_HOST_GNU_TYPE))
  DEB_CFLAGS_MAINT_APPEND += -mieee
endif

ifeq (arm-linux-gnueabihf,$(DEB_HOST_GNU_TYPE))
  DEB_CFLAGS_MAINT_APPEND += -mfpu=vfpv3-d16
endif

# Enable producing of debugging information
DEB_CFLAGS_MAINT_APPEND += -g

DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

export DEB_CFLAGS_MAINT_APPEND
export DEB_LDFLAGS_MAINT_APPEND

# some other helpful (for readability at least) shorthand variables
PHPIZE_BUILDDIR := /usr/lib/php/$(PHP_ZEND_VERSION)/build/

COMMON_CONFIG := \
		--build=$(DEB_BUILD_GNU_TYPE) \
		--host=$(DEB_HOST_GNU_TYPE) \
		--config-cache --cache-file=$(CURDIR)/config.cache \
		--libdir=\$${prefix}/lib/php \
		--libexecdir=\$${prefix}/lib/php \
		--datadir=\$${prefix}/share/php/$(PHP_NAME_VERSION) \
		--program-suffix=$(PHP_NAME_VERSION) \
		--sysconfdir=/etc \
		--localstatedir=/var \
		--mandir=/usr/share/man \
		--disable-all \
		--disable-debug \
		--disable-rpath \
		--disable-static \
		--with-pic \
		--with-layout=GNU \
		--without-pear \
		--enable-filter \
		--with-openssl \
		--with-password-argon2=/usr \
		--with-external-pcre \
		--enable-hash \
		  --with-mhash=/usr \
		--with-libxml \
		--enable-session \
		--with-sodium \
		--with-system-tzdata \
		--with-zlib=/usr \
		  --with-zlib-dir=/usr \
		$(CONFIGURE_ZTS) \
		$(CONFIGURE_DTRACE_ARGS) \
		$(CONFIGURE_PCRE_JIT)

# disable all SAPIs in extension build
export ext_config = \
		--prefix=/usr --enable-cli --disable-cgi --disable-phpdbg \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/apache2 \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/apache2/conf.d \
		$(COMMON_CONFIG)

export apache2_config = \
		--prefix=/usr --with-apxs2=/usr/bin/apxs2 --enable-cli --disable-cgi --disable-phpdbg \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/apache2 \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/apache2/conf.d \
		$(COMMON_CONFIG)

export cgi_config = \
		--prefix=/usr --enable-cgi --enable-cli --disable-phpdbg \
		--enable-force-cgi-redirect --enable-fastcgi \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/cgi \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/cgi/conf.d \
		$(COMMON_CONFIG) \
		--enable-pcntl

export cli_config = \
		--prefix=/usr --enable-cli --disable-cgi --disable-phpdbg \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/cli \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/cli/conf.d \
		$(COMMON_CONFIG) \
		--enable-pcntl \
		--with-libedit=shared,/usr

export embed_config = \
		--prefix=/usr --enable-embed --enable-cli --disable-cgi --disable-phpdbg \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/embed \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/embed/conf.d \
		$(COMMON_CONFIG) \
		--without-mm \
		--enable-pcntl

export fpm_config = \
		--prefix=/usr --enable-fpm --enable-cli --disable-cgi --disable-phpdbg \
		--sysconfdir=/etc/php/$(PHP_NAME_VERSION)/fpm \
		--with-fpm-user=www-data --with-fpm-group=www-data \
		--with-fpm-acl \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/fpm \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/fpm/conf.d \
		$(COMMON_CONFIG) \
		--with-libevent-dir=/usr \
		$(CONFIGURE_SYSTEMD) \
		$(CONFIGURE_APPARMOR)

export phpdbg_config = \
		--prefix=/usr --enable-phpdbg --enable-cli --disable-cgi \
		--with-config-file-path=/etc/php/$(PHP_NAME_VERSION)/phpdbg \
		--with-config-file-scan-dir=/etc/php/$(PHP_NAME_VERSION)/phpdbg/conf.d \
		$(COMMON_CONFIG) \
		--enable-pcntl \
		--with-libedit=shared,/usr

BUILTIN_EXTENSION_CHECK=$$e=get_loaded_extensions(); natcasesort($$e); \
			$$s="The following extensions are built in:"; \
			foreach($$e as $$i) { $$s .= " $$i"; } \
			echo("php:Extensions=" . wordwrap($$s . ".\n", 75, "\$${Newline}"));

include $(CURDIR)/debian/rules.d/*.mk

#extensions

ext_DEBS       := $(addprefix php$(PHP_NAME_VERSION)-,$(ext_PACKAGES))
ext_EXTENSIONS := $(foreach ext_package,$(ext_PACKAGES),$($(ext_package)_EXTENSIONS))
ext_config     += $(foreach ext_ext,$(ext_EXTENSIONS),$($(ext_ext)_config))

#$(info Enabled packages $(ext_DEBS))
#$(info Enabled extensions $(ext_EXTENSIONS))
#$(info Enabled config $(ext_config))

%:
	dh $@ --with systemd --with apache2 --without=build-stamp --without autoreconf $(PARALLEL)

PREPARE_FILES := $(addprefix debian/,$(shell cat debian/prepare-files))

prepared: prepared-stamp debian/control debian/source.lintian-overrides
prepared-stamp:
	$(SED) -i -e 's/EXTRA_VERSION=""/EXTRA_VERSION="-$(PHP_DEBIAN_REVISION)"/' configure.ac
	./buildconf --force
	touch prepared-stamp

unprepared:
	dh_testdir
	$(SED) -i -e 's/EXTRA_VERSION="-$(PHP_DEBIAN_REVISION)"/EXTRA_VERSION=""/' configure.ac
	-[ -f ext/ext_skel.in ] && mv ext/ext_skel.in ext/ext_skel
	rm -f prepared-stamp

override_dh_auto_clean: unprepared
	rm -f $(subst @PHP_VERSION@,$(PHP_NAME_VERSION),$(PREPARE_FILES))

	rm -rf test-results.txt

	# clean up autogenerated cruft
	cat debian/modulelist | while read module extname dsoname priority; do \
	    $(MODULE_PACKAGE) \
	    for cruft in postinst preinst prerm postrm; do \
	        rm -f debian/$${package}.$${cruft}; \
	    done; \
	done

	extdir=`debian/tmp/usr/bin/php-config$(PHP_NAME_VERSION) --extension-dir | cut -b2- `; \
	for sapi in $(REAL_TARGETS); do \
		$(SAPI_PACKAGE) \
		for cruft in preinst postinst prerm postrm links dirs triggers lintian-overrides; do \
			rm -f debian/$${package}.$${cruft}; \
		done; \
	done

	# clean build directories
	for target in $(TARGETS); do \
	  dh_auto_clean --builddirectory $${target}-build $(PARALLEL); \
	  rm -rf $${target}-build; \
	done

	# remove shared config.cache
	rm -f $(CURDIR)/config.cache

override_dh_auto_configure-indep:

override_dh_auto_configure-arch: prepared
	for target in $(TARGETS); do \
	  dh_auto_configure --builddirectory $${target}-build $(PARALLEL) -- $$(eval echo \$${$${target}_config}); \
	done

override_dh_auto_build-indep:

override_dh_auto_build-arch:
	for target in $(TARGETS); do \
	  dh_auto_build --builddirectory $${target}-build $(PARALLEL); \
	done

override_dh_auto_install:
	for target in $(TARGETS); do \
	  dh_auto_install --builddirectory $${target}-build $(PARALLEL) -- install INSTALL_ROOT=$(CURDIR)/debian/tmp; \
	done

PCNTL_FUNCTIONS := $(shell < ext/pcntl/php_pcntl.h $(SED) -ne "/^PHP_FUNCTION/ s/PHP_FUNCTION(\(.*\));/\1/;t end;d;:end p" | tr '\n' ',')

override_dh_auto_test-indep:

override_dh_auto_test-arch: test-results.txt

test-results.txt:
ifeq (yes,$(RUN_TESTS))
	mkdir -p temp_session_store
	extensions=""; \
	for f in $(CURDIR)/ext-build/modules/*.so; do \
	    ext=`basename "$$f"`; \
	    test -d "$(CURDIR)/ext/$${ext%.so}/tests" || continue; \
	    test "$$ext" != "imap.so" || continue; \
	    test "$$ext" != "interbase.so" || continue; \
	    test "$$ext" != "ldap.so" || continue; \
	    test "$$ext" != "odbc.so" || continue; \
	    test "$$ext" != "pgsql.so" || continue; \
	    test "$$ext" != "pdo_dblib.so" || continue; \
	    test "$$ext" != "pdo_firebird.so" || continue; \
	    test "$$ext" != "pdo_odbc.so" || continue; \
	    test "$$ext" != "pdo_pgsql.so" || continue; \
	    test "$$ext" != "snmp.so" || continue; \
	    test "$$ext" != "opcache.so" || continue; \
	    test "$$ext" != "mysqlnd.so" || continue; \
	    test "$$ext" != "mysqli.so" || continue; \
	    test "$$ext" != "pdo_mysql.so" || continue; \
	    test "$$ext" != "wddx.so" || continue; \
	    extensions="$$extensions -d extension=$$ext"; \
	done; \
	[ "$$extensions" ] || { echo "extensions list is empty"; exit 1; }; \
	env NO_INTERACTION=1 \
	    TEST_PHP_CGI_EXECUTABLE=$(CURDIR)/cgi-build/sapi/php-cgi \
	    TEST_PHP_EXECUTABLE=$(CURDIR)/cli-build/sapi/cli/php \
	$(CURDIR)/cli-build/sapi/cli/php run-tests.php \
		-n \
		-d extension_dir=$(CURDIR)/ext-build/modules/ \
		$$extensions | \
	tee test-results.txt
	rm -rf temp_session_store
	@for test in `find . -name '*.log' -a '!' -name 'config.log' -a '!' -name 'bootstrap.log' -a '!' -name 'run.log'`; do \
	    echo; \
	    echo -n "$${test#./}:"; \
	    cat $$test; \
	    echo; \
	done | tee -a test-results.txt
else
	echo 'nocheck found in DEB_BUILD_OPTIONS or unsupported architecture' | tee test-results.txt
endif

prepare-files-stamp:
	# Do this first so we don't overwrite any debhelper-generated files
	#
	# generate versioned files from versionless variants
	for file in $(PREPARE_FILES); do \
	    versionless=$$(echo $$file | $(SED) -e 's/@PHP_VERSION@//g'); \
	    versioned=$$(echo $$file | $(SED) -e 's/@PHP_VERSION@/$(PHP_NAME_VERSION)/g'); \
	    package=$$(echo $$file | $(SED) -e 's,^debian/,,;s/\..*$$//;s/@PHP_VERSION@/$(PHP_NAME_VERSION)/g'); \
	    < $${versionless} $(SED_REPLACEMENT) > $${versioned}; \
	    if [ -x $${versionless} ]; then chmod +x $${versioned}; fi; \
	done
	# generate config snippets and maintscripts for the different sapi implementations
	# from the templates
	for sapi in $(REAL_TARGETS); do \
	    $(SAPI_PACKAGE) \
	    mkdir -p "debian/tmp/usr/lib/php/$(PHP_NAME_VERSION)/sapi/"; \
	    touch "debian/tmp/usr/lib/php/$(PHP_NAME_VERSION)/sapi/$${sapi}"; \
	    for tmpl in postrm prerm postinst dirs install triggers bug-script bug-control; do \
	        < debian/php-sapi.$${tmpl} $(SED_REPLACEMENT) > debian/$${package}.$${tmpl}; \
	        if [ -x debian/php-sapi.$${tmpl} ]; then chmod +x debian/$${package}.$${tmpl}; fi; \
	    done; \
	    < debian/php-sapi.lintian-overrides $(SED_REPLACEMENT) | grep -E "^$${package}" > debian/$${package}.lintian-overrides; \
	done

	for module in $(ext_PACKAGES); do \
	  package=php$(PHP_NAME_VERSION)-$${module}; \
	  extensions=$$(eval echo \$${$${module}_EXTENSIONS}); \
	  description=$$(eval echo \$${$${module}_DESCRIPTION}); \
	  for tmpl in preinst postinst postrm prerm bug-script bug-control triggers dirs substvars lintian-overrides; do \
	      < debian/php-module.$${tmpl}.in \
		$(SED) -e "/\#EXTRA\#/ r debian/$${package}.$${tmpl}.extra" | \
		$(SED) -e "s,@package@,$${package},g"		\
	           -e "s,@extensions@,$${extensions},g"		\
	           -e "s,@module@,$${module},g"			\
	           -e "s|@description@|$${description}|g"	\
	           -e "s,@PHP_VERSION@,$(PHP_NAME_VERSION),g"	\
	           -e "s,@PHP_API@,$${phpapi},g" | \
		$(SED) -e '/\#EXTRA\#/ d' \
	      > debian/$${package}.$${tmpl}; \
	  done; \
	  provides=""; \
	  for dsoname in $${extensions}; do \
	    normalized=$$(echo $${dsoname} | sed -e 's/_/-/g'); \
	    priority=$$(eval echo \$${$${dsoname}_PRIORITY}); \
	    if [ -z "$${priority}" ]; then priority=20; fi; \
	    extension=$$(eval echo \$${$${dsoname}_EXTENSION}); \
	    if [ -z "$${extension}" ]; then extension=extension; fi; \
	    mkdir -p debian/tmp/usr/share/$${package}/$${module}/; \
	    $(SED) -e "s,@extname@,$${module}," \
	           -e "s,@dsoname@,$${dsoname}," \
	           -e "s,@extension@,$${extension}," \
	           -e "s,@priority@,$${priority}," \
	      < debian/php-module.ini.in \
	      > debian/tmp/usr/share/$${package}/$${module}/$${dsoname}.ini; \
	    echo "usr/lib/php/*/$${dsoname}.so" >> debian/$${package}.install; \
	    echo "usr/share/$${package}/$${module}/$${dsoname}.ini" >> debian/$${package}.install; \
	    if [ "$${normalized}" = "opcache" ]; then echo "opcache.jit=off" >> debian/tmp/usr/share/$${package}/$${module}/$${dsoname}.ini; fi; \
	    if [ "$${normalized}" != "gettext" ]; then provides="php-$${normalized}, $${provides}"; fi; \
	    if [ "$${module}" != "$${normalized}" ]; then provides="php$(PHP_NAME_VERSION)-$${normalized}, $${provides}"; fi; \
	  done; \
	  echo "php-$${module}:Provides=$${provides}" >> debian/$${package}.substvars; \
	done
	touch prepare-files-stamp

remove-files-stamp:
	# get rid of dreaded libtool files
	find debian/tmp/ -name '*.la' -delete
	# get rid of static versions of PHP modules (WTF?)
	rm -f debian/tmp/usr/lib/php/$(PHP_ZEND_VERSION)/*.a

	rm -rf \
	  debian/tmp/.filemap \
	  debian/tmp/.channels \
	  debian/tmp/.lock \
	  debian/tmp/.depdb* \
	  debian/tmp/usr/bin/pear* \
	  debian/tmp/usr/bin/pecl* \
	  debian/tmp/usr/share/php/.filemap \
	  debian/tmp/usr/share/php/.lock \
	  debian/tmp/usr/share/php/.depdb* \
	  debian/tmp/usr/share/php/*.php \
	  debian/tmp/usr/share/php/.registry/ \
	  debian/tmp/usr/share/php/.channels/ \
	  debian/tmp/usr/share/php/doc/ \
	  debian/tmp/usr/share/php/Archive/ \
	  debian/tmp/usr/share/php/Console/ \
	  debian/tmp/usr/share/php/Structures/ \
	  debian/tmp/usr/share/php/test/ \
	  debian/tmp/usr/share/php/XML/ \
	  debian/tmp/usr/share/php/OS/ \
	  debian/tmp/usr/share/php/PEAR/ \
	  debian/tmp/usr/share/php/data/ \
	  debian/tmp/etc/pear.conf
	# shipping duplicate files from other packages is hell for security audits
	rm -f \
	  debian/tmp$(PHPIZE_BUILDDIR)/config.guess \
	  debian/tmp$(PHPIZE_BUILDDIR)/config.sub \
	  debian/tmp$(PHPIZE_BUILDDIR)/libtool.m4 \
	  debian/tmp$(PHPIZE_BUILDDIR)/pkg.m4 \
	  debian/tmp$(PHPIZE_BUILDDIR)/ltmain.sh \
	  debian/tmp$(PHPIZE_BUILDDIR)/shtool
	touch remove-files-stamp

override_dh_installdirs: prepare-files-stamp
	dh_installdirs

override_dh_install-arch: remove-files-stamp prepare-fpm-pools
# Rename Apache2 SAPI
	mv -u debian/tmp/usr/lib/apache2/modules/libphp.so debian/tmp/usr/lib/apache2/modules/libphp$(PHP_NAME_VERSION).so
# Rename embed SAPI
	mv -u debian/tmp/usr/lib/php/libphp.so debian/tmp/usr/lib/libphp$(PHP_NAME_VERSION).so
# Install extra CGI-BIN
	install -d -m 755 debian/tmp/usr/lib/cgi-bin/
	ln debian/tmp/usr/bin/php-cgi$(PHP_NAME_VERSION) debian/tmp/usr/lib/cgi-bin/php$(PHP_NAME_VERSION)

	dh_install --fail-missing

# Install a helper script for checking PHP FPM configuration
	mkdir -p debian/$(PHP_FPM)/usr/lib/php/
	install -m 755 debian/$(PHP_FPM)-reopenlogs debian/$(PHP_FPM)/usr/lib/php/

	# sanitize php.ini files
	mkdir -p debian/$(PHP_COMMON)/usr/lib/php/$(PHP_NAME_VERSION)/
	cat php.ini-production | tr "\t" " " | \
	$(SED) -e'/session.gc_probability =/ s/1/0/g;' \
	    -e'/disable_functions =/ s/$$/ $(PCNTL_FUNCTIONS)/g;' \
	    -e'/expose_php =/ s/On/Off/g;' \
	  > debian/$(PHP_COMMON)/usr/lib/php/$(PHP_NAME_VERSION)/php.ini-production

	cat php.ini-production | tr "\t" " " | \
	$(SED) -e'/memory_limit =/ s/128M/-1/g;' \
	    -e'/session.gc_probability =/ s/1/0/g' \
	  > debian/$(PHP_COMMON)/usr/lib/php/$(PHP_NAME_VERSION)/php.ini-production.cli

	cat php.ini-development | tr "\t" " " | \
	$(SED) -e'/session.gc_probability =/ s/1/0/g;' \
	    -e'/disable_functions =/ s/$$/ $(PCNTL_FUNCTIONS)/g;' \
	  > debian/$(PHP_COMMON)/usr/lib/php/$(PHP_NAME_VERSION)/php.ini-development

ifeq (yes,$(RUN_TESTS))
	mkdir -p debian/$(PHP_COMMON)/usr/share/doc/$(PHP_COMMON)/
endif

	$(SED) -i -e's@-ffile-prefix-map=[^ ]*[ ]*@@g' \
		-e's@-fdebug-prefix-map=[^ ]*[ ]*@@g' \
		-e's@$(CURDIR)@/tmp/buildd/nonexistent@g' \
		debian/$(PHP_DEV)/usr/include/php/*/main/build-defs.h \
		debian/$(PHP_DEV)/usr/bin/php-config$(PHP_NAME_VERSION)

override_dh_installinit:
	dh_installinit --restart-after-upgrade

override_dh_systemd_start:
	dh_systemd_start --restart-after-upgrade

override_dh_apache2:
	for sapi in apache2 cgi fpm; do \
	    $(SAPI_PACKAGE) \
	    < debian/$${versionless}.apache2 $(SED_REPLACEMENT) > debian/$${package}.apache2; \
	done
	dh_apache2 --conditional=php_enable

override_dh_installdocs-indep:
	dh_installdocs -i

override_dh_installdocs-arch:
	dh_installdocs -p$(PHP_COMMON)
	dh_installdocs -a --remaining-packages --link-doc=$(PHP_COMMON)

override_dh_compress:
	dh_compress -Xphp.ini

override_dh_installchangelogs-arch:
	dh_installchangelogs -a -p$(PHP_COMMON) NEWS

override_dh_installchangelogs-indep:
	dh_installchangelogs -i NEWS

override_dh_strip:
	dh_strip --dbgsym-migration='php$(PHP_NAME_VERSION)-dbg' || dh_strip

override_dh_makeshlibs-arch:
	dh_makeshlibs -a -p$(PHP_LIBEMBED) -V '$(PHP_LIBEMBED) (>= $(PHP_MAJOR_VERSION).$(PHP_MINOR_VERSION))'

override_dh_gencontrol-arch:
	# Bail-out if PHPAPI has changed
	stored=$$(cat debian/phpapi); \
	for sapi in $(REAL_TARGETS); do \
	    $(SAPI_PACKAGE) \
	    $${sapi}-build/sapi/cli/php -n -r '$(BUILTIN_EXTENSION_CHECK)' \
	      >> debian/$${package}.substvars; \
	    phpapi=$$(sh $${sapi}-build/scripts/php-config --phpapi); \
	    if [ "$${phpapi}" != "$${stored}" ]; then \
	        echo "PHPAPI has changed from $${stored} to $${phpapi}, please modify debian/phpapi"; \
	        exit 1; \
	    fi; \
	    echo "php:Provides=phpapi-$${phpapi}" >> debian/$${package}.substvars; \
	done; \
	if dpkg --compare-versions $(LIBTOOL_VERSION) gt 2.4.6-0.1~; then \
	    echo "libtool:Depends=libtool (>= 2.4.6-0.1~)" >> debian/php$(PHP_NAME_VERSION)-dev.substvars; \
	else \
	    echo "libtool:Depends=libtool" >> debian/php$(PHP_NAME_VERSION)-dev.substvars; \
	fi
	dh_gencontrol -a

debian/control: debian/control.in debian/rules debian/changelog debian/source.lintian-overrides debian/rules.d/* debian/php-module.control.in
	$(SED) -e "s/@PHP_VERSION@/$(PHP_NAME_VERSION)/g" -e "s/@BUILT_USING@/$(BUILT_USING)/g" >$@ <$<
	for ext in $(sort $(ext_PACKAGES)); do \
	  package=php$(PHP_NAME_VERSION)-$${ext}; \
	  description=$$(eval echo \$${$${ext}_DESCRIPTION}); \
	  echo >>$@; \
	  $(SED) -e "s|@ext@|$${ext}|" -e "s|@package@|$${package}|" -e "s|@description@|$${description}|" >>$@ <debian/php-module.control.in; \
	done
	mkdir -p debian/tests
	for f in debian/tests.in/*; do \
	  t=$$(basename $${f}); \
	  < debian/tests.in/$${t} $(SED_REPLACEMENT) > debian/tests/$${t}; \
	done

debian/source.lintian-overrides: debian/source.lintian-overrides.in debian/rules debian/changelog
	$(SED) -e "s/@PHP_VERSION@/$(PHP_NAME_VERSION)/g" >$@ <$<

.PHONY: prepared unprepared debian/control debian/source.lintian-overrides