#!/usr/bin/make -f

include debian/make.mk
include /usr/share/dpkg/architecture.mk
# Use dpkg-buildflags to get hardening flags, and exclude non-hardening flags
dpkg_buildflags = $(and $(1),$(shell DEB_CFLAGS_MAINT_STRIP="$(shell DEB_BUILD_MAINT_OPTIONS=hardening=-all dpkg-buildflags --get $(1))" dpkg-buildflags --get $(1)))
$(call lazy,CFLAGS,$$(call dpkg_buildflags,CFLAGS))
$(call lazy,CPPFLAGS,$$(call dpkg_buildflags,CPPFLAGS))
$(call lazy,LDFLAGS,$$(call dpkg_buildflags,LDFLAGS))

CFLAGS += -Wall -pipe
LDFLAGS += -Wl,--as-needed

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
	CONFIGURE_FLAGS := --disable-optimize
else
	CONFIGURE_FLAGS := --enable-optimize
endif

ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
	CONFIGURE_FLAGS += --enable-debug
else
	CONFIGURE_FLAGS += --disable-debug --enable-debug-symbols
endif

ifeq (64,$(DEB_HOST_ARCH_BITS))
	CONFIGURE_FLAGS += --enable-64bit
endif
ifeq (x32,$(shell dpkg-architecture -qDEB_HOST_ARCH))
	CONFIGURE_FLAGS += --enable-x32
endif

ifneq (,$(findstring $(DEB_HOST_ARCH),armel armhf))
	CONFIGURE_FLAGS += --enable-thumb2
endif

PREPROCESS_FILES := $(wildcard debian/*.in)

$(PREPROCESS_FILES:.in=): %: %.in
	sed 's,@DEB_HOST_MULTIARCH@/,$(DEB_HOST_MULTIARCH:=/),g;s,@MULTIARCH_WILDCARD@/,$(if $(DEB_HOST_MULTIARCH),*/),g' $< > $@

%:
	dh --sourcedirectory=nspr $@

override_dh_auto_configure: $(PREPROCESS_FILES:.in=)
	for file in config.guess config.sub; do \
		sed -i '2!b;/^#/ i\exec "/usr/share/misc/'$$file'" "$$@"' nspr/build/autoconf/$$file; \
	done

	CFLAGS="$(CFLAGS)" \
	CPPFLAGS="$(CPPFLAGS)" \
	LDFLAGS="$(LDFLAGS)" \
	dh_auto_configure -- \
                    $(CONFIGURE_FLAGS) \
		    --prefix=/usr \
		    --libdir=/usr/lib/$(DEB_HOST_MULTIARCH) \
	            --build=$(DEB_BUILD_GNU_TYPE) \
	            --host=$(DEB_HOST_GNU_TYPE)

override_dh_auto_clean:
	dh_auto_clean

	rm -f $(PREPROCESS_FILES:.in=)
	for file in config.guess config.sub; do \
		sed -i '2!b;/^exec "/ d' nspr/build/autoconf/$$file; \
	done

override_dh_strip:
	dh_strip -a --dbg-package=libnspr4-dbg

override_dh_makeshlibs: /usr/share/debhelper/autoscripts/postinst-makeshlibs /usr/share/debhelper/autoscripts/postrm-makeshlibs
	dh_makeshlibs -a -- -c4
	cat /usr/share/debhelper/autoscripts/postinst-makeshlibs > debian/libnspr4.postinst.debhelper
	cat /usr/share/debhelper/autoscripts/postrm-makeshlibs > debian/libnspr4.postrm.debhelper

ifneq (,$(DEB_HOST_MULTIARCH))
override_dh_gencontrol:
	dh_gencontrol -- -Vmisc:Multi-Arch=same
endif
