#!/usr/bin/make -f

deb_source := $(shell dpkg-parsechangelog | sed -n 's/^Source: //p')
deb_version := $(shell dpkg-parsechangelog | sed -n 's/^Version: //p')
upstream_version := $(shell echo '$(deb_version)' | sed 's/.*://; s/-[^-]*$$//')
git_rev := $(shell echo '$(upstream_version)' | sed 's/.*+//')

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

DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)

ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
CROSS_COMPILE=
else
CROSS_COMPILE=$(DEB_HOST_GNU_TYPE)-
endif

# XXX for some reason, --remote doesn't work with gitorious so this needs to be
# run from a local checkout
# --remote=git://gitorious.org/x-loader/x-loader.git
get-orig-source:
	rm -rf $(deb_source)-$(upstream_version)
	rm -f $(deb_source)-$(upstream_version).orig.tar.gz
	git clone git://gitorious.org/x-loader/x-loader.git $(deb_source)-$(upstream_version)
	cd $(deb_source)-$(upstream_version) && git archive \
		--format=tar \
		--prefix=$(deb_source)-$(upstream_version)/ \
		$(git_rev) \
		| gzip >../$(deb_source)_$(upstream_version).orig.tar.gz
	rm -rf $(deb_source)-$(upstream_version)

override_dh_auto_configure:
	@

override_dh_auto_build:
	while read plat deb; do \
		mkdir -p debian/build/$$plat; \
		$(MAKE) O=$$PWD/debian/build/$$plat $${plat}_config; \
		$(MAKE) CROSS_COMPILE="$(CROSS_COMPILE)"  \
			CC="$(CROSS_COMPILE)gcc" O=$$PWD/debian/build/$$plat; \
	done <debian/platforms

override_dh_auto_install:
	while read plat deb; do \
	    install -D -m644 debian/build/$$plat/MLO \
		debian/x-loader-$$deb/usr/lib/x-loader/$$plat/MLO; \
	    install -D -m644 debian/build/$$plat/x-load.bin \
		debian/x-loader-$$deb/usr/lib/x-loader/$$plat/x-load.bin; \
	done <debian/platforms

%:
	dh $@
