.PHONY: all clean wheels venv virtualenv test

all: requirements venv

PYTHONPATH:=$(abspath .)  # Set python module path to source directory
PYTHON_EXE:=python3

# re-evaluate each time because there's no sensible way to check
# whether the python interpreter changed
$(eval $(shell $(PYTHON_EXE) utils/make_vars.py))

requirements: release-$(PYTHON_IMPL)-requirements.txt dev-$(PYTHON_IMPL)-requirements.txt

wheels: wheels/$(PYTHON_IMPL)/.done

venv: virtualenvs/$(PYTHON_IMPL)/.done
	ln -sf 'virtualenvs/$(PYTHON_IMPL)' venv

virtualenv: venv

test: venv
	venv/bin/pytest $(TEST_ARGS)

# -- docs handling

docs: docs-html

docs-%: venv
	$(MAKE) -C docs PATH="$$PWD/venv/bin:$$PATH" '$*'

# -- requirement file rules

release-$(PYTHON_IMPL)-requirements.txt: release-requirements.in
	'$(PYTHON_EXE)' -m piptools compile -v --annotate -o '$@.new' $<
	mv '$@.new' '$@'

# Pull in both files into one compiled development requirement set
dev-$(PYTHON_IMPL)-requirements.txt: release-requirements.in dev-requirements.in
	'$(PYTHON_EXE)' -m piptools compile -v --annotate -o '$@.new' release-requirements.in dev-requirements.in
	mv '$@.new' '$@'

# -- wheel building rules

wheels/$(PYTHON_IMPL)/.done: dev-$(PYTHON_IMPL)-requirements.txt
	mkdir -p 'wheels/$(PYTHON_IMPL)'
	'$(PYTHON_EXE)' -m pip wheel -w 'wheels/$(PYTHON_IMPL)' -r 'dev-$(PYTHON_IMPL)-requirements.txt'
	touch '$@'

# -- virtualenv rules

virtualenvs/$(PYTHON_IMPL)/bin/pip-sync:
	if test -e 'virtualenvs/$(PYTHON_IMPL)'; then rm -r 'virtualenvs/$(PYTHON_IMPL)'; else true; fi
	mkdir -p virtualenvs
	$(PYTHON_VENV) 'virtualenvs/$(PYTHON_IMPL)'
	'virtualenvs/$(PYTHON_IMPL)/bin/pip' install -I $(PYTHON_VENV_INSTALL)
	# for python-2 compatability
	#'virtualenvs/$(PYTHON_IMPL)/bin/pip' install -I "setuptools<45.0.0" 'pip<20.3' 'pip-tools<6'

virtualenvs/$(PYTHON_IMPL)/.done: dev-$(PYTHON_IMPL)-requirements.txt virtualenvs/$(PYTHON_IMPL)/bin/pip-sync wheels/$(PYTHON_IMPL)/.done
	virtualenvs/$(PYTHON_IMPL)/bin/pip-sync --no-index -f 'wheels/$(PYTHON_IMPL)' 'dev-$(PYTHON_IMPL)-requirements.txt'
	touch '$@'