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

altdir := /opt/alt/php85
testdir := /opt/alt/tests/alt-php85-pecl-xdebug_$(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)
php_extdir := $(_libdir)/php/modules
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:
	# Extract the PECL tarball and move source to root
	@version=$$(dpkg-parsechangelog | grep '^Version:' | cut -d' ' -f2 | cut -d'-' -f1); \
	tarball="xdebug-$${version}.tgz"; \
	echo "Extracting $$tarball"; \
	tar -xzf "$$tarball"; \
	srcdir=$$(ls -d xdebug-*/); \
	echo "Moving source from $$srcdir to root"; \
	mv "$${srcdir}"* .
	$(altdir)/usr/bin/phpize
	./configure --libdir=$(_libdir) \
				--with-php-config=$(altdir)/usr/bin/php-config \
				--with-libdir=$(DEB_HOST_MULTIARCH)
	make $(NJOBS)

	echo ";Enable xdebug extension module" > xdebug.ini
	echo "zend_extension=$(php_extdir)/xdebug.so" >> xdebug.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 xdebug.ini $(buildroot)$(_sysconfdir)/php.d.all/xdebug.ini

	dh_movefiles -palt-php85-pecl-xdebug \
		.$(_sysconfdir)/php.d.all/xdebug.ini \
		.$(php_extdir)/xdebug.so

override_dh_strip:
	# dh_strip doesn't strips debuginfo from debug/*.so files, which is bad for us
	# so we should copy dh_strip script and modify it
	# new Ubuntu: return if $fn=~m{debug/.*\.so};
	# old Ubuntu: return if $fn=~m/debug\/.*\.so/;
	cp $(shell which dh_strip) .
	sed -i '/debug\/.*\\.so/d' dh_strip
	sed -i '/debug\\\/.*\\.so/d' dh_strip
	./dh_strip

override_dh_auto_test:

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
