#!/usr/bin/make -f
# Copyright 2026 Canonical Ltd.
# SPDX-License-Identifier: Apache-2.0

# Uncomment to see every command that modifies files on the build system.
#export DH_VERBOSE = 1

include /usr/share/dpkg/architecture.mk

PACKAGING := $(CURDIR)/debian/packaging

%:
	dh $@

# There is no upstream build system to configure.
override_dh_auto_configure:

# Build the injector from source using Zig (ADR-007).
# Uses upstream's Makefile which invokes zig build with appropriate flags.
# Set ZIG_GLOBAL_CACHE_DIR to a writable location since sbuild runs as a
# non-existent user whose home directory doesn't exist.
# The zig0.15 package installs the binary as "zig0.15", so we create a
# wrapper directory with a "zig" symlink and prepend it to PATH.
ZIG_WRAPPER_DIR := $(CURDIR)/debian/.zig-wrapper

override_dh_auto_build:
	mkdir -p $(ZIG_WRAPPER_DIR)
	ln -sf /usr/bin/zig0.15 $(ZIG_WRAPPER_DIR)/zig
	PATH=$(ZIG_WRAPPER_DIR):$(PATH) \
	ZIG_GLOBAL_CACHE_DIR=$(CURDIR)/.zig-cache \
	    $(MAKE) -C $(CURDIR) ARCH=amd64

# Run the injector unit tests during the build (Debian best practice).
override_dh_auto_test:
ifneq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	@echo "Tests skipped due to DEB_BUILD_OPTIONS=nocheck"
else
	PATH=$(ZIG_WRAPPER_DIR):$(PATH) \
	ZIG_GLOBAL_CACHE_DIR=$(CURDIR)/.zig-cache \
	    $(MAKE) -C $(CURDIR) zig-unit-tests
endif

# Stage all files into debian/tmp/ for dh_install to split into packages.
# This runs after dh_prep (which wipes debian/tmp), so files survive into
# the dh_install step. Everything comes from the unpacked orig tarball;
# nothing is downloaded here.
override_dh_auto_install:
	# --- injector (built from source) ---
	install -d $(CURDIR)/debian/tmp/usr/lib/opentelemetry/injector
	install -m 0755 \
	    $(CURDIR)/so/libotelinject.so \
	    $(CURDIR)/debian/tmp/usr/lib/opentelemetry/injector/libotelinject.so

	# --- config files ---
	install -d $(CURDIR)/debian/tmp/etc/opentelemetry/injector/conf.d
	install -m 0644 $(PACKAGING)/common/injector/injector.conf \
	    $(CURDIR)/debian/tmp/etc/opentelemetry/injector/injector.conf
	install -m 0644 $(PACKAGING)/common/injector/default_env.conf \
	    $(CURDIR)/debian/tmp/etc/opentelemetry/injector/default_env.conf

	# --- injector lifecycle scripts ---
	install -d $(CURDIR)/debian/tmp/usr/share/opentelemetry-injector
	install -m 0755 $(PACKAGING)/common/scripts/postinstall-injector.sh \
	    $(CURDIR)/debian/tmp/usr/share/opentelemetry-injector/postinstall-injector.sh
	install -m 0755 $(PACKAGING)/common/scripts/preuninstall-injector.sh \
	    $(CURDIR)/debian/tmp/usr/share/opentelemetry-injector/preuninstall-injector.sh

# Clean up the zig wrapper directory created during build.
override_dh_clean:
	rm -rf $(ZIG_WRAPPER_DIR)
	dh_clean
