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

altdir := /opt/alt/php84
testdir := /opt/alt/tests/alt-php84-pecl-scoutapm_$(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//")
export CFLAGS := $(CPPFLAGS)
export CXXFLAGS := $(CPPFLAGS)
LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS)
export PATH := $(altdir)/usr/bin:${PATH}

CPPFLAGS += -Wno-error=array-bounds

export EXTRA_LDFLAGS=$(LDFLAGS)
export EXTRA_CFLAGS=$(CPPFLAGS)

buildroot := $(CURDIR)/debian/tmp
_sourcedir := debian/src
_sysconfdir := $(altdir)/etc
_libdir := $(altdir)/usr/lib/$(DEB_HOST_MULTIARCH)
_inifile	:= scoutapm.ini
NJOBS := -j$(shell getconf _NPROCESSORS_ONLN)

use_altcurl := $(shell ldd /opt/alt/php80/usr/bin/php | grep curl | grep "alt/curlssl" | wc -l)

ifeq ($(use_altcurl),1)
       export PKG_CONFIG_PATH=/opt/alt/curlssl/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/libcurl.pc
endif

%:
	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)* .
	$(altdir)/usr/bin/phpize
	./configure --libdir=$(_libdir) \
				--with-php-config=$(altdir)/usr/bin/php-config \
				--with-libdir=$(DEB_HOST_MULTIARCH)
	make $(NJOBS)

	echo ";Enable ScoutAPM extension module" > $(_inifile)
	echo "zend_extension=scoutapm.so" >> $(_inifile)

# fails on older OS on PHP80 only

override_dh_auto_install:
	mkdir -p $(buildroot)$(altdir)
	install -d $(buildroot)$(_sysconfdir)/php.d.all
	install -d $(buildroot)$(testdir)/tests
	make install INSTALL_ROOT=$(buildroot)
	install -D -m 644 $(_inifile) $(buildroot)$(_sysconfdir)/php.d.all/$(_inifile)
	cp tests/* $(buildroot)$(testdir)/tests/

	dh_movefiles -palt-php84-pecl-scoutapm \
		.$(_sysconfdir)/php.d.all/*.ini \
		.$(_libdir)/php/modules/*

	dh_movefiles -palt-php84-pecl-scoutapm-tests \
		.$(testdir)

override_dh_auto_test:

override_dh_missing:
	dh_missing --fail-missing

override_dh_auto_clean:
	rm -rf .cache
