#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# Debian 12 ships rustc 1.63; the cli feature pulls clap (MSRV 1.74).
# On Debian 12 build the library and FFI only, without the CLI binary.
# (stable /etc/debian_version is "12.x", not the codename)
IS_RUSTC163 := $(shell grep -qs '^12\.' /etc/debian_version && echo yes)

%:
	dh $@

override_dh_auto_build:
	# dpkg-source strips *.orig files (patch-backup convention) from the
	# repacked source, breaking cargo's vendored-checksum validation; the
	# complete vendor tree ships as a separate source file and is
	# extracted here (SOURCES path in OBS dsc builds, parent dir locally)
	tar -xf ../SOURCES/vendor.tar.xz 2>/dev/null || tar -xf ../vendor.tar.xz
	# upstream cdylib has no SONAME: inject a versioned one
	# -p targets: the workspace root is itself a package, so a bare
	# cargo build only compiles the root, not the ffi member
ifneq ($(IS_RUSTC163),yes)
	CARGO_NET_OFFLINE=true RUSTFLAGS="-C link-arg=-Wl,-soname,libstuffit_ffi.so.0" \
		cargo build --release --offline -p stuffit -p stuffit-ffi
else
	CARGO_NET_OFFLINE=true RUSTFLAGS="-C link-arg=-Wl,-soname,libstuffit_ffi.so.0" \
		cargo build --release --offline -p stuffit --no-default-features -p stuffit-ffi
endif

override_dh_auto_test:
ifneq ($(IS_RUSTC163),yes)
	CARGO_NET_OFFLINE=true cargo test --release --offline -p stuffit -p stuffit-ffi
else
	# bookworm: skip; example compilation needs newer toolchain features
endif

override_dh_auto_install:
	install -d debian/tmp/usr/bin \
		debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig
ifneq ($(IS_RUSTC163),yes)
	install -m0755 target/release/stuffit debian/tmp/usr/bin/stuffit
else
	# bookworm: no CLI binary; drop it from the install manifest
	sed -i '/usr\/bin\/stuffit/d' debian/stuffit-rs.install
endif
	install -m0644 target/release/libstuffit_ffi.a debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/
	install -m0755 target/release/libstuffit_ffi.so \
		debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/libstuffit_ffi.so.0
	ln -sf libstuffit_ffi.so.0 \
		debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/libstuffit_ffi.so
	install -Dm0644 stuffit-ffi/include/stuffit_ffi.h debian/tmp/usr/include/stuffit_ffi.h
	sed -e 's|^libdir=.*|libdir=/usr/lib/$(DEB_HOST_MULTIARCH)|' \
		stuffit-ffi/pkgconfig/stuffit-ffi.pc \
		> debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/stuffit-ffi.pc
