#!/usr/bin/make -f
#export DH_VERBOSE = 1

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# For multiarch
include /usr/share/dpkg/architecture.mk
# FOR DEB_VERSION_UPSTREAM
include /usr/share/dpkg/pkg-info.mk

FLAGS_ARGEO=-O3 -g -DNDEBUG

CMAKE_FLAGS = \
              -DCMAKE_BUILD_TYPE=RelWithDebInfo \
              -DCMAKE_C_FLAGS_RELWITHDEBINFO="$(FLAGS_ARGEO)" \
              -DCMAKE_CXX_FLAGS_RELWITHDEBINFO="$(FLAGS_ARGEO)" \
              -DLLAMA_BUILD_NUMBER=$(subst 0.0.,,$(DEB_VERSION_UPSTREAM)) \
              -DLLAMA_BUILD_COMMIT=Argeo \
              -DLLAMA_USE_SYSTEM_GGML=ON \
              \
              -DCMAKE_LIBRARY_PATH=/usr/libexec/$(DEB_TARGET_MULTIARCH)/ggml \
              \
              -DLLAMA_CURL=ON \
              -DLLAMA_BUILD_TOOLS=ON \
              -DLLAMA_BUILD_EXAMPLES=OFF \
              -DLLAMA_BUILD_TESTS=OFF \
              -DLLAMA_BUILD_SERVER=OFF

# Use build/ for output, so that it is in the .gitignore of upstream
%:
	dh $@ --buildsystem=cmake \
	 --builddirectory=build/$(DEB_TARGET_MULTIARCH)

override_dh_auto_configure-arch:
	dh_auto_configure -- $(CMAKE_FLAGS)

execute_after_dh_auto_install-arch:
	# Bash completion file
	mkdir -p completions
	LD_LIBRARY_PATH=debian/tmp/usr/lib/$(DEB_TARGET_MULTIARCH) \
		debian/tmp/usr/bin/llama-cli --device none --completion-bash \
		> completions/llama-cli

# Move executables to ggml's libexec, so that they can load the GGML backends
# and link them in usr/bin
	mkdir -p debian/tmp/usr/libexec/$(DEB_TARGET_MULTIARCH)/ggml
	for progname in debian/tmp/usr/bin/llama-*; do \
		progname_base=$$(basename $$progname); \
    	mv $$progname debian/tmp/usr/libexec/$(DEB_TARGET_MULTIARCH)/ggml/; \
		ln -s --relative -t debian/tmp/usr/bin \
		 debian/tmp/usr/libexec/$(DEB_TARGET_MULTIARCH)/ggml/$$progname_base; \
		[ "$$progname_base" != "llama-cli" ] || continue ; \
		ln -r -s completions/llama-cli completions/$$progname_base; \
	done

# No tests for now, as many need some kind of model we don't have
override_dh_auto_test:
	:
