#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
RUSTFLAGS += $(foreach flag,$(LDFLAGS),-C link-arg=$(flag))
export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS RUSTFLAGS

rust_cpu = $(subst i586,i686,$(if $(findstring -armhf-,-$(2)-),$(subst arm,armv7,$(1)),$(1)))
DEB_HOST_RUST_TYPE := $(call rust_cpu,$(DEB_HOST_GNU_CPU),$(DEB_HOST_ARCH))-unknown-$(DEB_HOST_GNU_SYSTEM)
DEB_TARGET_RUST_TYPE := $(call rust_cpu,$(DEB_TARGET_GNU_CPU),$(DEB_TARGET_ARCH))-unknown-$(DEB_TARGET_GNU_SYSTEM)

# Cargo looks for config in and writes cache to $CARGO_HOME/
export CARGO_HOME = $(CURDIR)/.cargohome
# Ask cargo to be verbose when building
export VERBOSE = 1

DEB_DESTDIR := $(CURDIR)/debian/tmp
VENDORDIR := $(CURDIR)/vendor
INDEXDIR := $(CURDIR)/vendor/index

HAVE_BOOTSTRAP_BINARY := $(shell ls -1 debian/bootstrap/$(DEB_HOST_RUST_TYPE)/ 2>/dev/null | wc -l)

%:
	dh $@ --with bash-completion

$(CURDIR)/.cargo/config:
	mkdir -p $(dir $@)
	echo "[source.crates-io]" >> $@
	echo "registry = 'https://github.com/rust-lang/crates.io-index'" >> $@
	echo "replace-with = 'vendored-sources'" >> $@
	echo "" >> $@
	echo "[source.vendored-sources]" >> $@
	echo "directory = '$(CURDIR)/vendor'" >> $@

override_dh_auto_configure: $(CURDIR)/.cargo/config
	cp -a $(CURDIR)/Cargo.lock $(CURDIR)/.Cargo.lock.orig

override_dh_auto_build:
ifneq (0,$(HAVE_BOOTSTRAP_BINARY))
	ln -s $(CURDIR)/debian/bootstrap/$(DEB_HOST_RUST_TYPE)/cargo $(CURDIR)/cargo-stage0
else
	ln -s `which cargo` $(CURDIR)/cargo-stage0
endif
	./configure \
		--prefix=/usr \
		--disable-debug \
		--enable-optimize \
		--local-rust-root=/usr \
		--cargo=$(CURDIR)/cargo-stage0
	# Build final cargo binary and docs
	$(MAKE)
ifeq (,$(findstring nodoc,$(DEB_BUILD_PROFILES)))
	$(MAKE) doc
	cd target/doc/ && rm -f jquery.js && ln -s /usr/share/javascript/jquery/jquery.js
endif

override_dh_auto_clean:
	-mv $(CURDIR)/.Cargo.lock.orig $(CURDIR)/Cargo.lock
	dh_auto_clean
	-$(RM) -r $(CURDIR)/target/ \
			$(CURDIR)/.cargo/ \
			$(CURDIR)/config.mk \
			$(CURDIR)/config.stamp \
			$(CURDIR)/Makefile \
			$(CURDIR)/cargo-stage0 \
			$(CARGO_HOME)

override_dh_auto_install:
	# We pick stuff directly from target/

override_dh_auto_test:
	# we don't run tests at the moment due to too many deps

