#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk

# Required to allow us to install to usr/local
export NO_PKG_MANGLE=true

# DEB_VERSION will look like a.b.c[.d]+ubuntuYY.MM[.x]
PACKAGE_MAJOR := $(shell echo $(DEB_VERSION) | cut -d. -f1)

# CUDA_TARGET_ARCH
# if DEB_HOST_ARCH is arm64, CUDA_TARGET_ARCH is sbsa
CUDA_TARGET_ARCH := $(shell if [ "$(DEB_HOST_ARCH)" = "arm64" ]; then echo "sbsa"; else echo "x86_64"; fi)

CUDA_VERSION := $(file < debian/cuda-version)
CUDA_MAJOR := $(shell echo $(CUDA_VERSION) | cut -d. -f1)
CUDA_MINOR := $(shell echo $(CUDA_VERSION) | cut -d. -f2)
CUDA_PATCH := $(shell echo $(CUDA_VERSION) | cut -d. -f3)

BIN_PKG_VERSION := $(shell echo $(DEB_VERSION) | cut -d- -f2- )

.PHONY: binary binary-arch binary-indep build build-arch build-indep clean install install-arch install-indep

get-orig-source:
	debian/scripts/get-orig-source

binary binary-arch binary-indep build build-arch build-indep clean install install-arch install-indep:
	export CUDA_TARGET_ARCH=$(CUDA_TARGET_ARCH); dh $@

override_dh_auto_configure:
	# No configuration needed

override_dh_auto_build:
	# No build needed - binary packages

override_dh_auto_test:
	# Skip tests

override_dh_auto_install:
	# Install files from upstream tarball based on architecture
	mkdir -p debian/tmp/
	# Copy architecture-specific directories
	if [ -d "$(DEB_TARGET_ARCH)" ]; then \
		cp -a $(DEB_TARGET_ARCH)/* debian/tmp/ || true; \
	fi

override_dh_install:
	cp debian/tmp/LICENSE debian/tmp/EULA
	mv debian/overridden_files/libnvperf_grfx_host.tegradotso debian/overridden_files/libnvperf_grfx_host.tegra.so
	export CUDA_TARGET_ARCH=$(CUDA_TARGET_ARCH); dh_install
	mv debian/overridden_files/libnvperf_grfx_host.tegra.so debian/overridden_files/libnvperf_grfx_host.tegradotso
	rm debian/tmp/EULA

override_dh_gencontrol:
	# Normal dh_gencontrol, but with packageMajor variable set
	dh_gencontrol -- "-VpackageMajor=$(PACKAGE_MAJOR)"

override_dh_dwz:
	# Skip dwz - not needed for repacking binaries, and causing some issues

override_dh_strip:
	# Skip stripping - not needed for repacking binaries, and causing some issues

override_dh_shlibdeps:
	 dh_shlibdeps -l$(shell pwd)/$(DEB_TARGET_ARCH)/lib

override_dh_usrlocal:
	# skip

# put this at the bottom, so it will override everything in this file
-include debian/per-package-rules.mk
