#!/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-xdiff_$(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)

xdiff_dir := $(CURDIR)/xdiff

# some static libs are built and placed here
local_install_dir := $(CURDIR)/local


%:
	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)* .


	mkdir $(xdiff_dir)
	tar xf debian/src/libxdiff-0.23.tar.gz -C $(xdiff_dir) --strip-components=1
	cd $(xdiff_dir); \
		./configure  --enable-static --disable-shared --with-pic; \
		make $(NJOBS); \
		make install DESTDIR=$(local_install_dir)/

	sed -i 's@SEARCH_PATH=.*@SEARCH_PATH="$(local_install_dir)/usr/local"@' config.m4 
	$(altdir)/usr/bin/phpize
	
	export CFLAGS+=" -I$(local_install_dir)/usr/local/include"; \
	export LDFLAGS+=" -L$(local_install_dir)/usr/local/lib"; \
		./configure --libdir=$(_libdir) \
				--with-php-config=$(altdir)/usr/bin/php-config \
				--with-libdir=$(DEB_HOST_MULTIARCH)
	make $(NJOBS)
	echo ";Enable xdiff extension module" > xdiff.ini
	echo "extension=xdiff.so" >> xdiff.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 xdiff.ini $(buildroot)$(_sysconfdir)/php.d.all/xdiff.ini
	install -d $(buildroot)$(testdir)/tests
	cp -r tests/* $(buildroot)$(testdir)/tests/
	dh_movefiles -palt-php85-pecl-xdiff \
		.$(_sysconfdir)/php.d.all/xdiff.ini \
		.$(php_extdir)/xdiff.so
	dh_movefiles -palt-php85-pecl-xdiff-tests \
		.$(testdir)

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

override_dh_strip_nondeterminism:
# left empty to save .png files in tests

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
