#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

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

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

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

DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk
CFLAGS+=$(CPPFLAGS)
CXXFLAGS+=$(CPPFLAGS)

BUILDDIR=build

%:
	dh $@ -B$(BUILDDIR)

CMAKE_COMMON_FLAGS = \
    -DCMAKE_LIBRARY_ARCHITECTURE="$(DEB_TARGET_MULTIARCH)" \
    -DCURRENT_GIT_VERSION="$(DEB_VERSION)" \
    -DBUILD_PYTHON=ON \
    -DBUILD_TESTS=ON

CMAKE_GENERIC_FLAGS = \
    $(CMAKE_COMMON_FLAGS) \
    -DARCH=generic \
    -DCMAKE_INSTALL_PREFIX=/usr

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

CMAKE_ICE40_NOQT_FLAGS = \
    $(CMAKE_ICE40_FLAGS) \
    -DBUILD_GUI=OFF \
    -DCMAKE_INSTALL_PREFIX=/noqt/usr

CMAKE_ICE40_QT_FLAGS = \
    $(CMAKE_ICE40_FLAGS) \
    -DBUILD_GUI=ON \
    -DCMAKE_INSTALL_PREFIX=/qt/usr

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 debian/$(BUILDDIR)
	dh_auto_clean

override_dh_auto_configure:
	cmake $(CMAKE_GENERIC_FLAGS) -S . -B debian/$(BUILDDIR)/generic
	cmake $(CMAKE_ICE40_NOQT_FLAGS) -S . -B debian/$(BUILDDIR)/ice40
	cmake $(CMAKE_ICE40_QT_FLAGS) -S . -B debian/$(BUILDDIR)/ice40-qt

override_dh_auto_build: build-generic build-ice40 build-ice40-qt

build-generic:
	make -C debian/$(BUILDDIR)/generic

build-ice40:
	make -C debian/$(BUILDDIR)/ice40

build-ice40-qt:
	make -C debian/$(BUILDDIR)/ice40-qt

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	make -C debian/$(BUILDDIR)/generic test
	make -C debian/$(BUILDDIR)/ice40 test
	make -C debian/$(BUILDDIR)/ice40-qt test
endif

override_dh_auto_install:
	DESTDIR=${CURDIR}/debian/tmp make -C debian/$(BUILDDIR)/generic install
	DESTDIR=${CURDIR}/debian/tmp make -C debian/$(BUILDDIR)/ice40 install
	DESTDIR=${CURDIR}/debian/tmp make -C debian/$(BUILDDIR)/ice40-qt install

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

override_dh_installexamples:
	dh_installexamples --exclude=.gitignore


.PHONY: build-generic build-ice40 build-ice40-qt
