#!/usr/bin/make -f
export DEB_BUILD_MAINT_OPTIONS = hardening=+all

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

GGUF_SITE = debian/python3-gguf/usr/lib/python3/dist-packages
GGUF_BIN  = debian/python3-gguf/usr/bin

CMAKE_FLAGS = \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DBUILD_SHARED_LIBS=ON \
  -DCMAKE_INSTALL_RPATH=/usr/lib/$(DEB_HOST_MULTIARCH)/llama \
  -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=OFF \
  -DLLAMA_LIB_INSTALL_DIR=lib/$(DEB_HOST_MULTIARCH)/llama \
  -DLLAMA_INCLUDE_INSTALL_DIR=include/llama \
  -DLLAMA_BUILD_NUMBER=9318 \
  -DLLAMA_BUILD_COMMIT=openKylin \
  -DLLAMA_USE_SYSTEM_GGML=OFF \
  -DGGML_NATIVE=OFF \
  -DGGML_BACKEND_DL=ON \
  -DGGML_CPU_ALL_VARIANTS=ON \
  -DLLAMA_BUILD_TESTS=ON \
  -DLLAMA_BUILD_TOOLS=ON \
  -DLLAMA_BUILD_EXAMPLES=ON \
  -DLLAMA_BUILD_SERVER=ON \
  -DLLAMA_CURL=ON

%:
	dh $@ --with python3

override_dh_auto_configure-arch:
	dh_auto_configure --buildsystem=cmake -- $(CMAKE_FLAGS)

override_dh_auto_configure-indep:
	:

override_dh_auto_build-arch:
	dh_auto_build --buildsystem=cmake

override_dh_auto_build-indep:
	:

# Best-effort man pages (help2man); never fail the build
execute_after_dh_auto_build-arch:
	-mkdir -p man/man1
	-for p in obj-*/bin/llama-* obj-*/bin/test-*; do \
	  b=$$(basename $$p); \
	  help2man --no-info --no-discard-stderr --section=1 --source=debian \
	    --version-string=$(DEB_VERSION_UPSTREAM) --name=$$b $$p \
	    > man/man1/$$b.1 2>/dev/null || rm -f man/man1/$$b.1; \
	done

override_dh_auto_install-arch:
	dh_auto_install --buildsystem=cmake

# python3-gguf is pure-python; install it manually (pybuild-plugin-pyproject
# is not installable on this distro). poetry entry points are recreated as
# small wrappers.
override_dh_auto_install-indep:
	install -d $(GGUF_SITE) $(GGUF_BIN)
	cp -r gguf-py/gguf $(GGUF_SITE)/
	# GUI tool needs PySide6 which is unavailable; drop it
	rm -f $(GGUF_SITE)/gguf/scripts/gguf_editor_gui.py
	set -e; for e in convert-endian:gguf_convert_endian dump:gguf_dump \
	                 set-metadata:gguf_set_metadata new-metadata:gguf_new_metadata; do \
	  name=gguf-$${e%%:*}; mod=$${e##*:}; \
	  { echo '#!/usr/bin/python3'; \
	    echo 'import sys'; \
	    echo "from gguf.scripts.$$mod import main"; \
	    echo 'if __name__ == "__main__":'; \
	    echo '    sys.exit(main())'; } > $(GGUF_BIN)/$$name; \
	  chmod 0755 $(GGUF_BIN)/$$name; \
	done

override_dh_auto_test:
	:

override_dh_auto_clean:
	-dh_auto_clean --buildsystem=cmake
	rm -rf man completions
	rm -f common/build-info.cpp
