#!/usr/bin/make -f

DEB_VERSION := $(shell dpkg-parsechangelog -S Version)
UPSTREAM_VERSION := $(shell echo $(DEB_VERSION) | sed -E 's/[.]?(ppa|db)[0-9]*$$//')
DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)

%:
	dh $@

override_dh_auto_build:
	# Source with vendored dependencies is in current directory
	# Ensure .cargo/config.toml exists for vendored dependencies
	if [ ! -f ".cargo/config.toml" ]; then \
		echo "Creating .cargo/config.toml for vendored sources"; \
		mkdir -p ".cargo"; \
		echo '[source.crates-io]' > ".cargo/config.toml"; \
		echo 'replace-with = "vendored-sources"' >> ".cargo/config.toml"; \
		echo '' >> ".cargo/config.toml"; \
		echo '[source.vendored-sources]' >> ".cargo/config.toml"; \
		echo 'directory = "vendor"' >> ".cargo/config.toml"; \
	fi
	# Fix vendor checksums for offline build
	for checksum in vendor/*/.cargo-checksum.json; do \
		if [ -f "$$checksum" ]; then \
			pkg=$$(cat "$$checksum" | grep -o '"package":"[^"]*"' | cut -d'"' -f4); \
			echo "{\"files\":{},\"package\":\"$$pkg\"}" > "$$checksum"; \
		fi; \
	done
	# Build with cargo using vendored dependencies
	cargo build --offline --release

override_dh_auto_install:
	install -Dm755 target/release/matugen \
		debian/matugen/usr/bin/matugen

override_dh_auto_clean:
	# Don't remove vendor - it contains vendored deps needed for arm64 build
	# Only clean build artifacts inside it
	rm -rf target
	dh_auto_clean
