#!/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
	# Build the bundled venv. Pip-installed scripts will get shebangs pointing
	# at $(CURDIR)/$(VENV)/bin/python — we strip that prefix after install.
	python3.11 -m venv $(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
