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

# Reproducible source tarballs: dpkg-source clamps mtimes newer than this
# value, but older checkout timestamps still differ across builders unless
# we normalise tracked files here (clean runs immediately before dpkg-source).
export SOURCE_DATE_EPOCH := $(shell dpkg-parsechangelog -STimestamp 2>/dev/null)

# Get the list of packages that should be built based on build profiles
PACKAGES := $(shell dh_listpackages)

VERSION_DIR := $(CURDIR)/debian/tmp/version
CONFIGURE_VERSIONED := $(CURDIR)/src/cmake/ConfigureVersionedFile.cmake
GENERATE_VERSION := $(CURDIR)/src/cmake/GenerateVersion.cmake

%:
	dh $@

.PHONY: override_dh_strip
override_dh_strip:
	dh_strip --exclude=rpi-imager

.PHONY: override_dh_clean
override_dh_clean:
	dh_clean
	rm -rf debian/rpi-imager debian/rpi-imager-cli debian/rpi-imager-embedded \
		debian/rpi-imager-amd64 debian/.debhelper debian/tmp \
		debian/com.raspberrypi.rpi-imager.metainfo.xml
	rm -f debian/files debian/*.substvars debian/*.debhelper.log \
		debian/debhelper-build-stamp debian/*debhelper*
	rm -f rpi-imager-embedded*.deb qt/language_filters.json \
		src/.qmlls.ini
	rm -f doc/performance/*.html
	@if [ -n "$(SOURCE_DATE_EPOCH)" ]; then \
		git ls-files -z | xargs -0 -r touch -hcd @$(SOURCE_DATE_EPOCH); \
		git ls-files | awk -F/ '{ \
			p=""; \
			for (i=1; i<NF; i++) { \
				p=(i>1 ? p "/" : "") $$i; \
				dirs[p]; \
			} \
		} END { for (d in dirs) print d }' | sort -u | \
			while IFS= read -r d; do \
				touch -hcd @$(SOURCE_DATE_EPOCH) "$$d"; \
			done; \
		touch -hcd @$(SOURCE_DATE_EPOCH) .; \
	fi

# Desktop .deb installs pre-built AppImages and does not run a full CMake
# build, but still needs metainfo.xml configured with the git version.
.PHONY: override_dh_auto_build
override_dh_auto_build:
ifneq (,$(filter rpi-imager,$(PACKAGES)))
	mkdir -p $(VERSION_DIR)
	cmake -DSOURCE_DIR=$(CURDIR) -DOUTPUT_DIR=$(VERSION_DIR) \
		-DGIT_EXECUTABLE=$$(command -v git) \
		-P $(GENERATE_VERSION)
	cmake -DVERSION_VARS_FILE=$(VERSION_DIR)/imager_version_vars.cmake \
		-DINPUT=$(CURDIR)/debian/com.raspberrypi.rpi-imager.metainfo.xml.in \
		-DOUTPUT=$(CURDIR)/debian/com.raspberrypi.rpi-imager.metainfo.xml \
		-P $(CONFIGURE_VERSIONED)
endif

# For the embedded package, install the vendored directory tree produced by
# create-embedded.sh into the package staging area.
override_dh_auto_install:
	dh_auto_install
ifneq (,$(filter rpi-imager-embedded,$(PACKAGES)))
	mkdir -p debian/rpi-imager-embedded
	cp -a debroot-embedded-*/opt debian/rpi-imager-embedded/
	cp -a debroot-embedded-*/usr debian/rpi-imager-embedded/
endif
