#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# for SOURCE_DATE_EPOCH
include /usr/share/dpkg/pkg-info.mk
DATE_MONTH_YEAR=$(shell env LC_ALL=C.UTF-8 date --utc --date=@${SOURCE_DATE_EPOCH} +"%B %Y")

# for DEB_HOST_GNU_TYPE
include /usr/share/dpkg/architecture.mk

# Do not run in parallel as different cmake invocations override each other's
# output. This also makes blhc fail.
# The underlying issue is that the upstream build system spawns cmake children
# via add_custom_command(COMMAND ${CMAKE_COMMAND}) so this is not even cmake's
# fault.
%:
	dh $@ --no-parallel

override_dh_auto_configure:
	dh_auto_configure -- -DPICO_SDK_PATH=/usr/src/pico-sdk -DUSE_PRECOMPILED=0

# CFLAGS are intentionally missing because 32 bit arm eabi5 firmware files are
# not given the hardening flags (which would not be supported)
execute_before_dh_auto_build:
	@echo 'blhc: ignore-line-regexp: .* -c /.*/xip_ram_perms/set_perms.c'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/otp_header_parser/otp_header_parse.cpp'
	@echo 'blhc: ignore-line-regexp: .* -c /usr/src/pico-sdk/.*'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/picoboot_flash_id/flash_id.c'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/xip_ram_perms/pico-sdk/src/rp2350/boot_stage2/bs2_default_padded_checksummed.S'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/picoboot_flash_id/pico-sdk/src/rp2040/boot_stage2/bs2_default_padded_checksummed.S'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/enc_bootloader/enc_bootloader.c'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/enc_bootloader/pico-sdk/src/rp2350/boot_stage2/bs2_default_padded_checksummed.S'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/enc_bootloader/aes.S'
	@echo 'blhc: ignore-line-regexp: .* -c /.*/enc_bootloader/hard_entry_point.S'
	@echo 'blhc: ignore-line-regexp: .* -o bs2_default.elf'
	@echo 'blhc: ignore-line-regexp: .* -o flash_id.elf'
	@echo 'blhc: ignore-line-regexp: .* -o otp_header_parse'
	@echo 'blhc: ignore-line-regexp: .* -o xip_ram_perms.elf'
	@echo 'blhc: ignore-line-regexp: .* -o enc_bootloader.elf'

override_dh_dwz:
	dh_dwz \
		--exclude=/usr/share/picotool/xip_ram_perms.elf \
		--exclude=/usr/share/picotool/enc_bootloader.elf

override_dh_strip:
	dh_strip \
		--exclude=/usr/share/picotool/xip_ram_perms.elf \
		--exclude=/usr/share/picotool/enc_bootloader.elf

execute_before_dh_installman:
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	# native build: verify that cached man pages didn't change
	./debian/manpages.sh verify "$(DEB_HOST_GNU_TYPE)" "$(DEB_VERSION_UPSTREAM)" "$(DATE_MONTH_YEAR)"
endif
	# if this was a cross-build, we can just use the cached files
	# if this was a native build, we verified its contents above
	set -e; for f in ./debian/man/*.md; do \
		pandoc "$$f" --standalone --to=man --output="./debian/man/$$(basename "$$f" .md).1" --metadata="footer:picotool $(DEB_VERSION_UPSTREAM)" --metadata="date: $(DATE_MONTH_YEAR)"; \
	done

execute_after_dh_auto_clean:
	rm -f picotool.1 ./xip_ram_perms/xip_ram_perms.elf
