#!/usr/bin/make -f

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

%:
	dh $@

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 to keep the package small (and remove any .pyc that
	# binary-encodes the buildroot path).
	find $(VENV) -type d -name '__pycache__' -prune -exec rm -rf {} +
	find $(VENV) -name '*.pyc' -delete
	# Rewrite the buildroot path out of every TEXT file in the venv (shebangs,
	# pyvenv.cfg, pip-bootstrap script bodies). grep -I skips binaries.
	grep -rlI "$(CURDIR)/$(DESTDIR)" $(VENV) 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
