#!/usr/bin/make -f

export PDP_EXTRA_CFLAGS = -fPIC -Wno-error $(CPPFLAGS) $(CFLAGS)
DPKG_EXPORT_BUILDFLAGS = 1
DEB_BUILD_MAINT_OPTIONS=hardening=-format,+fortify,+stackprotector,+relro
export DEB_BUILD_MAINT_OPTIONS
include /usr/share/dpkg/buildflags.mk


ifeq ($(DEB_BUILD_ARCH),i386)
DEB_CONFIGURE_EXTRA_FLAGS = --enable-mmx
DEB_EXTRA_CFLAGS = -mmmx
BUILD_SCAF = yes
endif

ifeq ($(DEB_BUILD_ARCH),amd64)
DEB_CONFIGURE_EXTRA_FLAGS = --enable-mmx
DEB_EXTRA_CFLAGS = -mmmx
BUILD_SCAF = yes
endif

%:
	dh $@ --with autoreconf

override_dh_autoreconf:
	dh_autoreconf --as-needed

override_dh_auto_configure:
	dh_auto_configure -- $(DEB_CONFIGURE_EXTRA_FLAGS)
	dh_auto_configure -Dscaf -- $(DEB_CONFIGURE_EXTRA_FLAGS)

override_dh_auto_build:
	dh build --before dh_auto_build
	make pdp_all
	make -C opengl \
		LDFLAGS="$(LDFLAGS)" \
		PDP_EXTRA_CFLAGS="$(CFLAGS) $(DEB_EXTRA_CFLAGS)" \
		PDP_EXTRA_CPPFLAGS="$(CPPFLAGS)"
	[ -z $(BUILD_SCAF) ] || \
	make -C scaf \
		LDFLAGS="-fPIC $(LDFLAGS)" \
		PDP_CFLAGS="$(CPPFLAGS) -fPIC $(CFLAGS)"
	[ -z $(BUILD_SCAF) ] || \
	cp scaf/rules/carules.scafo scaf/rules/default.scafo
	docbook-to-man debian/pdp-config.sgml > pdp-config.1
	dh build --after dh_auto_build

override_dh_auto_clean:
	dh clean --before dh_auto_clean
	[ ! -f opengl/Makefile.config ] || make -C opengl clean
	[ ! -f scaf/Makefile.config ] || make -C scaf clean
	[ ! -f Makefile.config ] || make clean
	-$(RM) -rf bin/pdp-config include/pdp_config.h
	-$(RM) -f Makefile.config config.log config.status
	-$(RM) -f scaf/Makefile.config scaf/config.log scaf/config.status
	-$(RM) -f pdp-config.1
	-$(RM) -f scaf/rules/default.scafo
	dh clean --after dh_auto_clean

override_dh_installchangelogs:
	dh_installchangelogs CHANGES.LOG

override_dh_shlibdeps:
	find debian/pd-pdp -name "*.pd_linux" -exec \
		dpkg-shlibdeps -Tdebian/pd-pdp.substvars {} +
	find debian/pd-3dp -name "*.pd_linux" -exec \
		dpkg-shlibdeps -Tdebian/pd-3dp.substvars {} +
	[ -z $(BUILD_SCAF) ] || \
	find debian/pd-scaf -name "*.pd_linux" -exec \
		dpkg-shlibdeps -Tdebian/pd-scaf.substvars {} +

override_dh_strip:
	dh_strip
	find debian -name "*.pd_linux" -exec \
		strip --remove-section=.comment --remove-section=.note --strip-unneeded {} +
	[ -z $(BUILD_SCAF) ] || \
	find debian -name "*.scafo" -exec \
		strip --remove-section=.comment --remove-section=.note --strip-unneeded {} +

override_dh_fixperms:
	dh_fixperms
	find debian -name '*.pd_linux' -exec \
		chmod 0644 {} +
	find debian -name '*.scafo' -exec \
		chmod 0644 {} +
