#!/usr/bin/make -f
export SHELL := /bin/bash
export DH_VERBOSE = 1
export DH_OPTIONS = -v

altdir := /opt/alt/php56
testdir := /opt/alt/tests/alt-php56-pecl-brotli_$(shell dpkg-parsechangelog | grep Version: | cut -d' ' -f2-)

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
CPPFLAGS = $(shell dpkg-buildflags --get CFLAGS | sed -e "s/-Wformat//;s/-Werror=format-security//")
CPPFLAGS += -I$(CURDIR)/brotli/c/include
LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS)
export PATH := $(altdir)/usr/bin:${PATH}

buildroot := $(CURDIR)/debian/tmp
_sysconfdir := $(altdir)/etc
_libdir := $(altdir)/usr/lib/$(DEB_HOST_MULTIARCH)
NJOBS := -j$(shell getconf _NPROCESSORS_ONLN)

export EXTRA_LDFLAGS=$(LDFLAGS)
export EXTRA_CFLAGS=$(CPPFLAGS)
export CFLAGS := $(CPPFLAGS)
export CXXFLAGS := $(CPPFLAGS)

.DEFAULT:
	dh $@

override_dh_auto_build:
	# PECL tarballs contain package.xml on the same level as source dir (usually called modname-1.1.1),
	# so debhelper doesn't unpack its contents in work dir.
	# Move files from the first created source dir to current dir.
	mv $(shell ls -trd -- */ | head -n 1)* .

	$(altdir)/usr/bin/phpize
	./configure --libdir=$(_libdir) \
				--with-php-config=$(altdir)/usr/bin/php-config \
				--with-libdir=$(DEB_HOST_MULTIARCH)
	make $(NJOBS)

	echo ";Enable brotli extension module" > brotli.ini
	echo "extension=brotli.so" >> brotli.ini

override_dh_auto_install:
	mkdir -p $(buildroot)$(altdir)
	install -d $(buildroot)$(_sysconfdir)/php.d.all

	make install INSTALL_ROOT=$(buildroot)

	install -D -m 644 brotli.ini $(buildroot)$(_sysconfdir)/php.d.all/brotli.ini

	if [ -d tests ] || [ -d brotli/c ] || [ -d brotli/tests ]; then \
		install -d $(buildroot)$(testdir); \
		if [ -d tests ]; then \
			install -d $(buildroot)$(testdir)/tests; \
			cp -a tests/* $(buildroot)$(testdir)/tests/; \
		fi; \
		if [ -d brotli/c ]; then \
			install -d $(buildroot)$(testdir)/brotli; \
			cp -a brotli/c $(buildroot)$(testdir)/brotli/; \
		fi; \
		if [ -d brotli/tests ]; then \
			install -d $(buildroot)$(testdir)/brotli; \
			cp -a brotli/tests $(buildroot)$(testdir)/brotli/; \
		fi; \
	fi

	dh_movefiles -palt-php56-pecl-brotli \
		.$(_sysconfdir)/php.d.all/brotli.ini \
		.$(_libdir)/php/modules/brotli.so

	if [ -d $(buildroot)$(testdir) ]; then \
		dh_movefiles -palt-php56-pecl-brotli-tests \
			.$(testdir); \
	fi

override_dh_auto_test:

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
