#!/usr/bin/make -f

PACKAGE = $(shell dh_listpackages)
TMP     = $(CURDIR)/debian/$(PACKAGE)

ARCHLIB := $(shell perl -MConfig -e 'print $$Config{vendorarch}')

# this number comes from IMAGER_API_VERSION in imexttypes.h
# it is used for the Provides: perl-imagerapi-XX relationship
# it needs to be updated manually because of the implications on the archive

IMAGERAPI_VERSION = 5
IMAGERAPI_DETECTED_VERSION =

_DETECTION_CMD := cpp `perl -MExtUtils::Embed -e ccopts` debian/get-imagerapi-version.cpp | sh
# GNU-make required for the use of define here.
define _ABORTBUILD
	echo Aborting due to Imager API version mismatch - configured $(IMAGERAPI_VERSION), detected $(IMAGERAPI_DETECTED_VERSION)
	exit 1
endef
# GNU-make required for the use of define here.
define _RUNBUILD
	dh_auto_build
	printf "%s\n%s\n%s\n" \
	  "# this variable is the preferred interface for generating a perl-imagerapi-* dependency." \
	  "# See #693003." \
	  "PERL_IMAGERAPI_DEPENDS=perl-imagerapi-$(IMAGERAPI_VERSION)" \
	 > debian/perl-imagerapi.make
	sed "s,@IMAGERAPI_VERSION@,$(IMAGERAPI_VERSION)," debian/dh_perl_imager.in >debian/dh_perl_imager
	chmod +x debian/dh_perl_imager
	pod2man debian/dh_perl_imager debian/dh_perl_imager.1
endef

%:
	dh $@

# GNU-make required for the eval ... construct here.
getapi_version: imconfig.h
	: $(eval IMAGERAPI_DETECTED_VERSION := $(shell $(_DETECTION_CMD)))
	@echo IMAGERAPI_DETECTED_VERSION detected as $(IMAGERAPI_DETECTED_VERSION)

override_dh_auto_configure:
	dh_auto_configure -- --disable=TT-fonts

# GNU-make required for the use of "in-line conditional *if*", and filter-out function.
override_dh_auto_build: getapi_version
	$(if $(filter-out $(IMAGERAPI_VERSION),$(IMAGERAPI_DETECTED_VERSION)),$(_ABORTBUILD),$(_RUNBUILD))

override_dh_auto_install:
	dh_auto_install
	# Imager::Font::Type1 is a wrapper around Imager::Font::T1
	# which we don't build; cf. #638762
	$(RM) -v $(TMP)/$(ARCHLIB)/Imager/Font/Type1.pm \
		$(TMP)/usr/share/man/man3/Imager::Font::Type1.3pm

override_dh_installexamples:
	dh_installexamples
	sed -i '1s|^#!perl|#!/usr/bin/perl|' $(TMP)/usr/share/doc/libimager-perl/examples/*

override_dh_fixperms:
	dh_fixperms
	chmod a+x $(TMP)/usr/share/doc/$(PACKAGE)/examples/*.pl

override_dh_compress:
	dh_compress -Xexamples

override_dh_clean:
	dh_clean
	rm -rf $(CURDIR)/_Inline

override_dh_gencontrol:
	dh_gencontrol -- -Vperl-imagerapi-version=$(IMAGERAPI_VERSION)

.PHONY: getapi_version
