#!/usr/bin/make -f

CROSS :=
DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
ifneq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	CROSS :=  $(DEB_HOST_GNU_TYPE)
endif

# this outputs 0 or 1 depending on whether a piece of assembly can be compiled
# with the *default* gcc flags; this is used to test the toolchain *default*
# configuration
check_asm = $(shell echo 'void foo(void) { __asm__ volatile("$(1)"); }' |   \
	$(CROSS)gcc -x c -c - -o /dev/null 2>/dev/null && echo 1 || echo 0)

CFLAGS   = $(shell dpkg-buildflags --get CFLAGS)
CFLAGS  += $(shell dpkg-buildflags --get CPPFLAGS)
CFLAGS  += "-I/usr/include/$(DEB_HOST_GNU_TYPE)"   # fixes #676029
LDFLAGS  = $(shell dpkg-buildflags --get LDFLAGS)

ifeq ($(DEB_HOST_ARCH_CPU),arm)
	# whether the toolchain *default* configuration enables ARMv7
	v7_asm := dmb
	has_v7 := $(call check_asm, $(v7_asm))

	ifneq ($(has_v7),1)
		CFLAGS += -march=armv7-a
	endif
endif

%:
	dh $@ --parallel --with=autotools-dev,bash-completion

override_dh_auto_configure:
	dh_auto_configure -- --host="$(DEB_HOST_GNU_TYPE)" --enable-tls \
		CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"

override_dh_auto_test:
	: # do nothing for now

override_dh_auto_build:
	dh_auto_build --parallel
	$(MAKE) -C docs html-docs
	$(MAKE) -C docs man-pages

override_dh_strip:
	dh_strip --dbg-package=valgrind-dbg

target=$(CURDIR)/debian/valgrind
override_dh_install:
	$(MAKE) install prefix=$(CURDIR)/debian/tmp/usr
	dh_install -pvalgrind -Xlibmpiwrap
	mv -f $(target)/usr/bin/valgrind $(target)/usr/bin/valgrind.bin
	mv -f ${target}/usr/bin/valgrind.sh $(target)/usr/bin/valgrind
	dh_install --remaining-packages

override_dh_installchangelogs:
	dh_installchangelogs NEWS
