#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/buildopts.mk

CHANGELOG_DATE ?= $(shell LC_ALL=C date -u -d @$(SOURCE_DATE_EPOCH) +"%d %B %Y")

export DH_VERBOSE=1
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

BUILDDIR=debian/build
MAKEFILE := $(firstword $(MAKEFILE_LIST))

COMPONENTS=generic ice40-qt ice40

%:
	dh $@

CMAKE_FLAGS_COMMON := \
    -DCURRENT_GIT_VERSION="$(DEB_VERSION)" \
    -DBUILD_PYTHON=ON \
    -DBUILD_TESTS=ON

CMAKE_FLAGS_generic := \
    $(CMAKE_COMMON_FLAGS) \
    -DARCH=generic

CMAKE_FLAGS_ice40 := \
    $(CMAKE_COMMON_FLAGS) \
    -DARCH=ice40 \
    -DICEBOX_DATADIR=/usr/share/fpga-icestorm/chipdb \
    -DICEBOX_ROOT=/usr/share/fpga-icestorm/chipdb \

CMAKE_FLAGS_ice40-qt := $(CMAKE_FLAGS_ice40) -DBUILD_GUI=ON
CMAKE_FLAGS_ice40    := $(CMAKE_FLAGS_ice40) -DBUILD_GUI=OFF

HELP2MAN_FLAGS = \
    --name="Next Generation Place and Route" \
    --version-string="$(DEB_VERSION)" \
    --section=1 \
    --manual="General Commands" \
    --no-info \
    --no-discard-stderr

override_dh_auto_clean:
	rm -rf $(BUILDDIR)
	rm -f debian/nextpnr-generic.1 debian/nextpnr-ice40.1
	dh_auto_clean

override_dh_auto_configure override_dh_auto_build override_dh_auto_test override_dh_auto_install:
	+$(MAKE) -f$(MAKEFILE) $(DEB_BUILD_OPTION_PARALLEL:%=-j%) \
                $(patsubst %,$(subst override_dh_auto_,,$@)/%,$(COMPONENTS))

override_dh_installman:
	help2man $(HELP2MAN_FLAGS) debian/nextpnr-generic/usr/bin/nextpnr-generic > debian/nextpnr-generic.1
	help2man $(HELP2MAN_FLAGS) debian/nextpnr-ice40-qt/usr/bin/nextpnr-ice40 > debian/nextpnr-ice40.1
	dh_installman

override_dh_installexamples:
	dh_installexamples --exclude=.gitignore

configure/%:
	dh_auto_configure -B$(BUILDDIR)/$* -- $(CMAKE_FLAGS_$*)

# HACK: dh_auto_build strips the MAKEFLAGS jobserver option. Prevent this
# by calling make manually.
build/%:
	cd $(BUILDDIR)/$* && exec $(MAKE) "INSTALL=install --strip-program=true"

test/%:
	dh_auto_test -B$(BUILDDIR)/$*

install/%:
	dh_auto_install -B$(BUILDDIR)/$* --destdir=$(CURDIR)/debian/nextpnr-$*
