#!/usr/bin/make -f

export DH_VERBOSE=1

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

DEB_VERSION := $(shell dpkg-parsechangelog -SVersion | sed 's/-[0-9]*$$//')
UPSTREAM_VERSION := $(DEB_VERSION)
SOFTWARE_NAME := sheldon

export CARGO_HOME=$(CURDIR)/.cargo-home
export LIBZ_SYS_STATIC=0

%:
	dh $@

override_dh_auto_build:
	@if [ ! -d vendor ]; then \
		echo "vendor/ not found, attempting to extract from SOURCES..."; \
		if [ -f /usr/src/packages/SOURCES/$(SOFTWARE_NAME)-$(UPSTREAM_VERSION)-vendor.tar.gz ]; then \
			tar -xzf /usr/src/packages/SOURCES/$(SOFTWARE_NAME)-$(UPSTREAM_VERSION)-vendor.tar.gz; \
			echo "vendor/ extracted successfully"; \
		else \
			echo "ERROR: vendor tarball not found in /usr/src/packages/SOURCES/"; \
			exit 1; \
		fi; \
	fi

	@test -d vendor || (echo "ERROR: vendor/ directory still not found" && exit 1)

	RUSTFLAGS="-C link-arg=-Wl,--as-needed" cargo build --release --frozen --offline

	@test -f target/release/$(SOFTWARE_NAME) || (echo "ERROR: binary not built" && exit 1)
	@echo "==> Binary built successfully: $(SOFTWARE_NAME)"

override_dh_auto_install:
	install -Dm755 target/release/$(SOFTWARE_NAME) $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/bin/$(SOFTWARE_NAME)
	install -Dm644 LICENSE-MIT $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/share/doc/$(SOFTWARE_NAME)/copyright

override_dh_auto_test:

override_dh_strip:
