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

altdir := /opt/alt/php74
testdir := /opt/alt/tests/alt-php74-pecl-stomp_$(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}


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

extension_dir := $(CURDIR)/.libs

phpXY := $(altdir)/usr/bin/php

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


%:
	dh $@

override_dh_auto_build:
	mv $(shell ls -trd -- */ | head -n 1)* .
	for f in $$(find tests -name '*.phpt'); do \
		if grep -q '^--INI--' "$$f"; then \
			sed -i '/^--INI--/a stomp.default_broker=tcp://127.0.0.1:61613' "$$f"; \
		else \
			sed -i 's/^--FILE--/--INI--\nstomp.default_broker=tcp:\/\/127.0.0.1:61613\n--FILE--/' "$$f"; \
		fi; \
	done
	# Tests added in stomp 2.x that the CoilMQ smoke broker cannot satisfy:
	# 003-connect/003 expects an auth error on CONNECT (CoilMQ accepts any login).
	rm tests/003-connect/003.phpt
	# The 009-readFrame family is timing-sensitive against CoilMQ's async
	# delivery and flakes on any platform (different subsets per run);
	# 009-readFrame/006 additionally expects a pure MESSAGE frame stack.
	rm -rf tests/009-readFrame
	$(altdir)/usr/bin/phpize
	./configure --libdir=$(_libdir) \
				--with-php-config=$(altdir)/usr/bin/php-config \
				--with-libdir=$(DEB_HOST_MULTIARCH) \
				--enable-stomp
	make $(NJOBS)
	echo ";Enable stomp extension module" > stomp.ini
	echo "extension=stomp.so" >> stomp.ini

override_dh_auto_install:
	mkdir -p $(buildroot)$(altdir)
	install -d $(buildroot)$(_sysconfdir)/php.d.all
	install -d $(buildroot)$(_sysconfdir)/php.d.std
	make install INSTALL_ROOT=$(buildroot)
	install -D -m 644 stomp.ini $(buildroot)$(_sysconfdir)/php.d.all/stomp.ini
	install -D -m 644 stomp.ini $(buildroot)$(_sysconfdir)/php.d.std/stomp.ini
	install -d $(buildroot)$(testdir)/tests
	if [ -d tests ]; then cp -r tests/* $(buildroot)$(testdir)/tests/; fi
	dh_movefiles -palt-php74-pecl-stomp \
		.$(_sysconfdir)/php.d.all/stomp.ini \
		.$(_sysconfdir)/php.d.std/stomp.ini \
		.$(php_extdir)/stomp.so
	dh_movefiles -palt-php74-pecl-stomp-tests \
		.$(testdir)

override_dh_auto_test:
	$(altdir)/usr/bin/php -d 'extension_dir=$(extension_dir)' -d 'extension=stomp.so' -m | grep ^Stomp$$

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
