#!/usr/bin/make -f
NPROC   := $(shell nproc)
BUILDDIR := build_deb
TRIPLET := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
PYVER   := $(shell python3 -c 'import sysconfig; print(sysconfig.get_python_version())')
FULLVER := 1.27.0
SOVER   := 1
RVV_MARCH := -march=rv64gcv_zfh_zvfh_zba_zicbop_zihintpause -mabi=lp64d
TMP    := $(CURDIR)/debian/tmp
LIBDIR := $(TMP)/usr/lib/$(TRIPLET)

%:
	dh $@

override_dh_auto_configure:
	# configuration handled by build.py in the build step

override_dh_auto_build:
	python3 tools/ci_build/build.py \
	  --build_dir $(BUILDDIR) --config Release --parallel $(NPROC) \
	  --build_shared_lib --enable_pybind --build_wheel \
	  --skip_tests --skip_submodule_sync \
	  --compile_no_warning_as_error --allow_running_as_root \
	  --cmake_deps_mirror_dir /home/openkylin/nvme/deb/ort-deps-mirror \
	  --cmake_extra_defines \
	    onnxruntime_BUILD_UNIT_TESTS=OFF \
	    CMAKE_C_FLAGS="$(RVV_MARCH)" \
	    CMAKE_CXX_FLAGS="$(RVV_MARCH)"

override_dh_auto_test:
	# upstream tests skipped for packaging build

override_dh_auto_install:
	# ---- shared library -> libonnxruntime1 ----
	install -d $(LIBDIR)
	cp -a $(BUILDDIR)/Release/libonnxruntime.so.$(FULLVER) $(LIBDIR)/
	ln -sf libonnxruntime.so.$(FULLVER) $(LIBDIR)/libonnxruntime.so.$(SOVER)
	ln -sf libonnxruntime.so.$(SOVER)   $(LIBDIR)/libonnxruntime.so
	# ---- providers shared library -> libonnxruntime-providers ----
	cp -a $(BUILDDIR)/Release/libonnxruntime_providers_shared.so $(LIBDIR)/
	# ---- public headers -> libonnxruntime-dev ----
	install -d $(TMP)/usr/include
	cp -a include/onnxruntime $(TMP)/usr/include/
	# ---- Python module -> python3-onnxruntime ----
	install -d $(TMP)/usr/lib/python3/dist-packages
	python3 -m pip install --no-deps --no-index --no-compile --break-system-packages \
	  --target=$(TMP)/usr/lib/python3/dist-packages $(BUILDDIR)/Release/dist/*.whl
	# de-duplicate: point bundled libs in capi at the multiarch shared library
	for f in $(TMP)/usr/lib/python3/dist-packages/onnxruntime/capi/libonnxruntime.so.*; do \
	  [ -e "$$f" ] && ln -sf /usr/lib/$(TRIPLET)/$$(basename "$$f") "$$f" || true; \
	done
	rm -f $(TMP)/usr/lib/python3/dist-packages/onnxruntime/capi/libonnxruntime_providers_*.so*
	# ---- console script -> onnxruntime-tools ----
	install -d $(TMP)/usr/bin
	printf '#!/usr/bin/python3\nimport sys\nfrom onnxruntime.tools.onnxruntime_test import main\nif __name__ == "__main__":\n    sys.exit(main())\n' > $(TMP)/usr/bin/onnxruntime_test
	chmod 0755 $(TMP)/usr/bin/onnxruntime_test

override_dh_makeshlibs:
	# providers lib is a dlopen plugin without an SONAME; do not generate shlibs for it
	dh_makeshlibs --exclude=/usr/lib/$(TRIPLET)/libonnxruntime_providers_

override_dh_auto_clean:
	rm -rf $(BUILDDIR)
