#!/usr/bin/make -f
# -*- makefile -*-
#export DH_VERBOSE=1

# To bootstrap new architectures, comment out the
# "ldc" dependency in d/control or use the stage1
# build profile.
# Alternatively, set `BOOTSTRAP` to yes to unconditionally
# enable bootstrap mode.
BOOTSTRAP = yes
ifeq (,$(wildcard /usr/bin/ldmd2))
	# if there is no LDC, we have to bootstrap
	BOOTSTRAP = yes
endif

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_HOST_ARCH=$(shell dpkg-architecture -qDEB_HOST_ARCH)

CFLAGS += $(CPPFLAGS)
CXXFLAGS += $(CPPFLAGS)

LDC_BUILD_FLAGS = -DINCLUDE_INSTALL_DIR='/usr/lib/ldc/${DEB_HOST_MULTIARCH}/include/d'
BOOTSTRAP_LDC_FLAGS = -DD_FLAGS=-w\;-relocation-model=pic

ifeq ($(DEB_HOST_ARCH),armhf)
LDC_BUILD_FLAGS += -DD_COMPILER_FLAGS=-mattr=-neon
BOOTSTRAP_LDC_FLAGS = -DD_FLAGS=-w\;-relocation-model=pic\;-mattr=-neon
endif

ifneq ($(filter stage1,$(DEB_BUILD_PROFILES)),)
	# we need to bootstrap in stage1, as no prebuilt LDC is available
	BOOTSTRAP = yes
endif

BOOTSTRAP_LDC_DIR := $(CURDIR)/bootstrap
BOOTSTRAP_LDC_BUILD_DIR := $(BOOTSTRAP_LDC_DIR)/b

BOOTSTRAP_LDMD = ldmd2
ifeq ($(BOOTSTRAP), yes)
	BOOTSTRAP_LDMD = $(BOOTSTRAP_LDC_BUILD_DIR)/bin/ldmd2
endif

%:
	dh $@ --parallel

override_dh_auto_configure:
ifeq ($(BOOTSTRAP), yes)
	# Build the C++-only old compiler for bootstrapping
	dh_auto_configure -D$(BOOTSTRAP_LDC_DIR) -B$(BOOTSTRAP_LDC_BUILD_DIR) -- $(BOOTSTRAP_LDC_FLAGS)
	dh_auto_build -B$(BOOTSTRAP_LDC_BUILD_DIR)
endif

	# Configure the actual LDC version
	[ -d build-static ] || mkdir build-static
	dh_auto_configure -B$(CURDIR)/build-static -- \
			-DD_COMPILER=$(BOOTSTRAP_LDMD) \
			-DBUILD_SHARED_LIBS=OFF $(LDC_BUILD_FLAGS)

	[ -d build-shared ] || mkdir build-shared
	dh_auto_configure -B$(CURDIR)/build-shared -- \
			-DD_COMPILER=$(BOOTSTRAP_LDMD) \
			-DBUILD_SHARED_LIBS=ON $(LDC_BUILD_FLAGS)

override_dh_auto_build:
	dh_auto_build -Bbuild-static
	dh_auto_build -Bbuild-shared

override_dh_auto_install:
	(cd build-static && $(MAKE) install DESTDIR="$(CURDIR)/debian/tmp")
	(cd build-shared && $(MAKE) install DESTDIR="$(CURDIR)/debian/tmp")

override_dh_install:
	dh_install --list-missing

override_dh_installman:
	dh_installman debian/ldc2.1 debian/ldmd2.1

override_dh_clean:
	rm -rf build-static build-shared
	rm -f configure-stamp build-stamp
	dh_clean

override_dh_strip:
	dh_strip -X.a
