#!/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)

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

override_dh_auto_configure:
	cat xfree-4.supp debian/debian.supp > debian.supp
	./configure CFLAGS="$(CFLAGS)" \
		--prefix=/usr \
		--mandir=\$${prefix}/share/man \
		--enable-tls

override_dh_auto_test:
	: # do nothing for now

override_dh_clean:
	dh_clean
	$(RM) debian.supp

target=$(CURDIR)/debian/valgrind
override_dh_install:
	$(MAKE) install prefix=$(CURDIR)/debian/valgrind/usr
	# Debian stuff
	cp -f debian/debian-libc6-dbg.supp $(target)/usr/lib/valgrind
	mv -f $(target)/usr/bin/valgrind $(target)/usr/bin/valgrind.bin
	cp -f debian/valgrind.sh $(target)/usr/bin/valgrind
	chown root.root $(target)/usr/bin/valgrind.bin $(target)/usr/bin/valgrind
	chmod 755 $(target)/usr/bin/valgrind.bin $(target)/usr/bin/valgrind
	install -p -m644 debian.supp $(target)/usr/lib/valgrind
	install -p -d -m755 $(target)/usr/share/doc/valgrind/html
	install -p -m644 debian/valgrind.bash $(target)/etc/bash_completion.d/valgrind

%:
	dh $@ --parallel --with autoreconf
