#!/usr/bin/make -f
DTMP = $(CURDIR)/debian/tmp
HIP_VERSION = $(shell sed -n '1s/.*(\([0-9.]\+\)-.*).*/\1/p' debian/changelog)

# Environment
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -lpthread
export HIP_CLANG_PATH = /usr/bin
export ROCM_PATH = /usr
export DEVICE_LIB_PATH = /usr/lib/$(DEB_HOST_MULTIARCH)/amdgcn/bitcode
export HIP_CLANG_HCC_COMPAT_MODE = 1
# Verbose mode, for help with debuging build problems
#export HIPCC_COMPILE_FLAGS_APPEND += -v
#export HIPCC_LINK_FLAGS_APPEND += -v
#export HIPCC_VERBOSE = 7

# List of supported architecture to proceed to offload.  This is a work around
# failure to build from source on autobuilders
OFFLOAD_ARCHS = gfx803
OFFLOAD_ARCHS+= gfx900
OFFLOAD_ARCHS+= gfx906
OFFLOAD_ARCHS+= gfx1030
OFFLOAD_ARCHS_STR = $(foreach ARCH, $(OFFLOAD_ARCHS), --offload-arch=$(ARCH))

%:
	dh $@

override_dh_auto_configure-arch:
	dh_auto_configure -- \
		-DCMAKE_BUILD_TYPE=Release \
		-DHIP_COMMON_DIR=$(shell realpath hip) \
		-DAMD_OPENCL_PATH=$(shell realpath opencl) \
		-DROCCLR_PATH=$(shell realpath clr) \
		-DROCM_PATH=/usr \
		-DFILE_REORG_BACKWARD_COMPATIBILITY=OFF \
		-DCMAKE_HIP_ARCHITECTURES=gfx906 \
		-DOFFLOAD_ARCH_STR=" $(OFFLOAD_ARCHS_STR)" \
		-DHIP_PLATFORM=amd

# ROCm from 5.0 has dwarf 5 section headers:
# https://github.com/ROCm-Developer-Tools/hipamd/issues/17
override_dh_dwz-arch:
	@echo "I: No debug symbols for now"
#	dh_dwz -- --dwarf-5

override_dh_auto_test-arch:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	dh_auto_build -- build_tests
	set -e \
	; if [ -r /dev/kfd ] \
	; then LD_LIBRARY_PATH=$(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/lib \
	       dh_auto_test --no-parallel -- \
	; else echo "W: /dev/kfd unreadable: no available AMD GPU." \
	;      echo "W: tests skipped." \
	; fi
endif

execute_before_dh_install-arch:
	# fix interpreter path
	sed -i '1s@^#!/usr/bin/env perl$$@#!/usr/bin/perl@' $(DTMP)/usr/bin/*
	# remove unnecessary DT_RUNPATH
	find debian/ -name 'libhiprtc-builtins.so.*'
	patchelf --remove-rpath $(DTMP)/usr/lib/*/libhiprtc-builtins.so.*
	patchelf --remove-rpath $(DTMP)/usr/lib/*/libamdhip64.so.*
	# rename .hipVersion
	mkdir -p -- $(DTMP)/usr/share/hip
	mv -- $(DTMP)/usr/bin/.hipVersion $(DTMP)/usr/share/hip/version

override_dh_auto_configure-indep:
	:

override_dh_auto_build-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	sed 's@\(OUTPUT_DIRECTORY\s*=\).*@\1 ../../@' hip/docs/doxygen-input/doxy.cfg > hip/docs/doxygen-input/debian.cfg
	cd hip/docs; HIP_PATH=.. doxygen doxygen-input/debian.cfg
endif

override_dh_auto_test-indep:
	:

override_dh_auto_install-indep:
	:
