#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export TOOLCFLAGS = -Wno-error -g

include /usr/share/dpkg/default.mk

COREBOOT_UTILS = cbfstool cbmem ifdtool intelvbttool kbc1126 nvramtool
ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 i386 x32))
COREBOOT_UTILS += bucts ectool intelmetool inteltool msrtool pmh7tool superiotool
endif

# Ubuntu 25.04 uses -O3 by default for amd64 & ppc64el
# but the build is failing with -O3 LP: #2099764
ifeq ($(shell dpkg-vendor --derives-from Ubuntu && echo yes),yes)
ifneq (,$(filter $(DEB_HOST_ARCH),amd64 ppc64el))
export DEB_CFLAGS_MAINT_APPEND += -O2
export DEB_CFLAGS_MAINT_STRIP += -O3
endif
endif

%:
	dh $@ --with sphinxdoc

override_dh_auto_configure:
	# util/msrtool/configure is hardcoded in several places (e.g. PREFIX=/usr/local)
	# replace it with a simple substitution. Previously was copied from d/Makefile
	sed -e "s#@VERSION@#${DEB_VERSION}#g" -e "s#@CC@#${CC}#g" -e "s#@CFLAGS@#${CFLAGS}#g" \
		-e "s#@LDFLAGS@#${LDFLAGS} -lpci#g" -e "s#@INSTALL@#install#g" -e "s#@PREFIX@#/usr#g" \
		util/msrtool/Makefile.in > util/msrtool/Makefile

override_dh_auto_build:
	set -e; \
	for f in $(COREBOOT_UTILS); do \
		$(MAKE) -C util/$$f;   \
	done
ifeq (,$(findstring nodoc, $(DEB_BUILD_OPTIONS)))
	# Build docs
	PYTHONPATH=. DEB_VERSION=$(DEB_VERSION) http_proxy='http://127.0.0.1:9/' \
			sphinx-build -N -E -bhtml Documentation build/html
endif

override_dh_clean:
	# TAGS gets cleaned by builtin db_clean, but this is upstream tracked
	dh_auto_clean
	dh_clean --exclude=src/sbom/TAGS

execute_before_dh_install-arch:
ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 i386 x32))
	dh_install util/bucts/bucts usr/sbin
endif

override_dh_sphinxdoc:
ifeq (,$(findstring nodoc,$(DEB_BUILD_OPTIONS)))
	dh_sphinxdoc -p coreboot-utils-doc
endif
