#!/usr/bin/make -f

DESTDIR := debian/eth-validator-stats
VENV    := $(DESTDIR)/opt/eth-validator-stats/venv

%:
	dh $@

# Skip shlibdeps scanning of the bundled python-build-standalone interpreter
# and the venv. libpython3.so uses $ORIGIN-relative RPATH which dpkg-shlibdeps
# can't resolve, and the bundle is self-contained by design — its private libs
# must not contribute to the .deb's external dependency declarations.
override_dh_shlibdeps:
	dh_shlibdeps -Xopt/eth-validator-stats

override_dh_auto_install:
	# Only create /opt and /usr/bin here. /etc/eth-validator-stats and
	# /var/lib/eth-validator-stats are created in postinst so the package
	# does NOT own them — that way dpkg won't touch user-created config
	# or state files on `apt remove`.
	mkdir -p $(DESTDIR)/opt/eth-validator-stats \
	         $(DESTDIR)/usr/bin
	# Bundle a self-contained python-build-standalone interpreter via uv.
	# This drops the runtime dependency on system python3.11.
	uv python install --install-dir $(DESTDIR)/opt/eth-validator-stats/python 3.11
	# Locate the installed interpreter (uv places it under a versioned dir).
	PBS_PYTHON=`find $(DESTDIR)/opt/eth-validator-stats/python -type f -name python3.11 | head -n1`; \
	  test -n "$$PBS_PYTHON" || { echo "ERROR: no python3.11 found after uv install"; exit 1; }; \
	  $$PBS_PYTHON -m venv --copies $(VENV); \
	  $(VENV)/bin/pip install --no-cache-dir .
	# Drop activation scripts (not needed at runtime; ExecStart calls the venv
	# binary directly) so they don't carry the buildroot path into the .deb.
	rm -f $(VENV)/bin/activate $(VENV)/bin/activate.csh \
	      $(VENV)/bin/activate.fish $(VENV)/bin/activate.nu \
	      $(VENV)/bin/activate.ps1
	# Strip caches across the whole bundled tree (.pyc files binary-encode
	# the buildroot path; clearing them avoids stale paths in shipped .pyc).
	find $(DESTDIR)/opt/eth-validator-stats -type d -name '__pycache__' -prune -exec rm -rf {} +
	find $(DESTDIR)/opt/eth-validator-stats -name '*.pyc' -delete
	# Rewrite the buildroot path out of every TEXT file in the bundled tree.
	# Walk the whole /opt/eth-validator-stats (both venv AND the
	# python-build-standalone base interpreter) — _sysconfigdata*.py in the
	# PBS tree otherwise carries the buildroot path. grep -I skips binaries.
	grep -rlI "$(CURDIR)/$(DESTDIR)" $(DESTDIR)/opt/eth-validator-stats 2>/dev/null \
	    | xargs -r sed -i 's|$(CURDIR)/$(DESTDIR)||g'
	# /usr/bin entrypoint symlink.
	ln -sf /opt/eth-validator-stats/venv/bin/eth-validator-stats \
	       $(DESTDIR)/usr/bin/eth-validator-stats
