#!/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-msgpack_$(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//")
LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS)
export PATH := $(altdir)/usr/bin:${PATH}

CPPFLAGS += -Wno-error=array-bounds

buildroot := $(CURDIR)/debian/tmp
_sourcedir := debian/src
_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)

%:
	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.
	# We should move files from that dir to current. Source dir is the first created one, debian/ is created later.
	mv $(shell ls -trd -- */ | head -n 1)* .

	# Causes null byte in output, and it's incompatible with test system on CL
	rm -f tests/bug013.phpt
	rm -f tests/issue023.phpt
	rm -f tests/issue067.phpt
	rm -f tests/issue107.phpt
	rm -f tests/issue139.phpt

	# Doesn't work without session dir, and it's not available in all alt-php's without LVE
	rm -f tests/issue132.phpt

	# Fails on old msgpack
	rm -f tests/018.phpt
	rm -f tests/030.phpt
	rm -f tests/040.phpt
	rm -f tests/040d.phpt

	rm -f tests/041.phpt


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

	echo ";Enable msgpack extension module" > msgpack.ini
	echo "extension=msgpack.so" >> msgpack.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 msgpack.ini $(buildroot)$(_sysconfdir)/php.d.all/msgpack.ini
	install -d $(buildroot)$(testdir)/tests
	cp tests/* $(buildroot)$(testdir)/tests/

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

	dh_movefiles -palt-php56-pecl-msgpack-tests \
		.$(testdir)

	# Manually install header files for -dev package on Debian 13 (make install doesn't do it)
	install -d $(buildroot)$(altdir)/usr/include/php/ext/msgpack
	install -m 644 php_msgpack.h $(buildroot)$(altdir)/usr/include/php/ext/msgpack/
	dh_movefiles -palt-php56-pecl-msgpack-dev \
		.$(altdir)/usr/include

override_dh_auto_test:

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
