#!/usr/bin/make -f

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
U_BOOT_ARCHITECTURES ?= $(shell grep-dctrl -F Package -X u-boot --show-field Architecture debian/control --no-field-names)

ifneq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
export CROSS_COMPILE ?= $(DEB_HOST_GNU_TYPE)-
endif

# support parallel build using DEB_BUILD_OPTIONS=parallel=N
ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  MAKEFLAGS += -j$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

# the upstream build passes LDFLAGS directly to ld instead of calling gcc for
# linking; so instead of passing -Wl,foo in LDFLAGS as in automake builds, one
# should set LDFLAGS to foo directly
comma := ,
LDFLAGS := $(patsubst -Wl$(comma)%,%,$(LDFLAGS))

%:
	dh $@ --parallel

override_dh_auto_build:
ifeq ($(DEB_HOST_ARCH),$(findstring $(DEB_HOST_ARCH), $(U_BOOT_ARCHITECTURES)))
	set -e; sed -n 's/^$(DEB_HOST_ARCH)[[:space:]]\+//p' debian/targets \
	    | while read platform targets; do \
	        builddir=`pwd`/debian/build/$$platform; \
	        mkdir -p $$builddir; \
		for target in $$targets ; do \
	        $(MAKE) O=$$builddir $${platform}_config; \
		$(MAKE) O=$$builddir $$target; \
		done ; \
		install -m 644 $$builddir/u-boot $$builddir/uboot.elf; \
	        $(CROSS_COMPILE)strip --remove-section=.comment \
	            $$builddir/uboot.elf; \
		$(MAKE) O=$$builddir HOSTCC=$(CROSS_COMPILE)gcc HOSTSTRIP=$(CROSS_COMPILE)strip env ; \
		$(CROSS_COMPILE)strip --remove-section=.comment $$builddir/tools/env/fw_printenv ; \
		ln -s fw_printenv $$builddir/tools/env/fw_setenv ; \
	done
endif

ifeq ($(CROSS_COMPILE),)
	# board-independent tools
	$(MAKE) HOSTCC=$(CROSS_COMPILE)gcc HOSTSTRIP=$(CROSS_COMPILE)strip \
	    tools-only
	$(CROSS_COMPILE)strip --remove-section=.comment tools/mkimage
endif

override_dh_auto_test override_dh_auto_install:
	# skip tests.

override_dh_clean:
	rm -rf debian/build/
	dh_clean
