#!/usr/bin/make -f
COMMA = ,

include /usr/share/dpkg/buildopts.mk

export CXX        = hipcc
export CC         = hipcc
export VERBOSE    = 1
export DH_VERBOSE = 1

export DEB_BUILD_MAINT_OPTIONS     = hardening=+all optimize=-lto
export DPKG_GENSYMBOLS_CHECK_LEVEL = 4

export ROCM_PATH=/usr
export HIP_PATH=/usr
export HIP_DEVICE_LIB_PATH=/usr/lib/llvm-21/lib/clang/21/amdgcn/bitcode

# filter incompatible options from affecting device code
CXXFLAGS := $(subst -fstack-protector-strong,-Xarch_host -fstack-protector-strong,$(CXXFLAGS))
CXXFLAGS := $(subst -fcf-protection,-Xarch_host -fcf-protection,$(CXXFLAGS))
# https://bugs-devel.debian.org/cgi-bin/bugreport.cgi?bug=1016936
# Use DWARF4 for dwz compatibility (dwz doesn't support DWARF5 yet)
CXXFLAGS += -gdwarf-4

GPU_TARGETS = "gfx908;gfx90a;gfx942;gfx950;gfx1100;gfx1101;gfx1102;gfx1151;gfx1200;gfx1201"
# rocWMMA doesnt support all architectures
#	-DGPU_TARGETS="$(shell rocm-target-arch --sep ';')"

# Limit the parallel jobs based on the available memory
ifneq (,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS))))
  NCPUS := $(subst parallel=,,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS))))
else
  NCPUS := $(DEB_BUILD_OPTION_PARALLEL)
endif
MEM_PER_CPU = 2100

NJOBS := $(shell mt=`awk '/^(MemAvail|SwapFree)/ { mt += $$2 } END {print mt}' /proc/meminfo`; \
		awk -vn=$(NCPUS) -vmt=$$mt -vm=$(MEM_PER_CPU) \
		'END { mt/=1024; n2 = int(mt/m); print n==1 || n2<=1 ? 1 : n2<=n ? n2 : n }' < /dev/null)

CMAKE_FLAGS = \
	-DCMAKE_BUILD_TYPE=Release \
	-DROCM_PATH=$(ROCM_PATH) \
	-DROCWMMA_BUILD_DOCS=ON \
	-DROCWMMA_BUILD_SAMPLES=OFF \
	-DBUILD_OFFLOAD_COMPRESS=ON \
	-DHIP_PLATFORM=amd \
	-DGPU_TARGETS=$(GPU_TARGETS) \
	-DROCWMMA_USE_SYSTEM_GOOGLETEST=ON

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- $(CMAKE_FLAGS)

override_dh_auto_build:
	dh_auto_build -- -j$(NJOBS)

override_dh_auto_configure-indep:
	:

execute_after_dh_auto_build-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	http_proxy='127.0.0.1:9' \
	https_proxy='127.0.0.1:9' \
	rocm-docs-build -r $(shell dpkg-parsechangelog -S Version | sed 's/[+-].*//')
	rm -rf build/html/_static/fonts
	rm -rf build/html/_static/vendor
endif
