PORT ?= 30000
HOST ?= 127.0.0.1
PAGE ?= /

.PHONY: run
run:
	@URL="http://$(HOST):$(PORT)$(PAGE)"; \
	echo "Serving H5 at $$URL"; \
	if curl -fsS "http://$(HOST):$(PORT)/__h5_dev_server__/health" 2>/dev/null | grep -q "ok"; then \
		echo "H5 dev server is already running on http://$(HOST):$(PORT)/"; \
		open "$$URL"; \
		exit 0; \
	fi; \
	if curl -fsS "http://$(HOST):$(PORT)/" >/dev/null 2>&1; then \
		echo "Port $(PORT) is occupied by a server without the H5 API proxy."; \
		echo "Stop that process, then run make run again."; \
		exit 1; \
	fi; \
	python3 scripts/h5_dev_server.py --host "$(HOST)" --port "$(PORT)" --directory "$$(pwd)" & \
	SERVER_PID=$$!; \
	trap 'kill $$SERVER_PID 2>/dev/null || true' INT TERM EXIT; \
	for i in 1 2 3 4 5 6 7 8 9 10; do \
		if curl -fsS "http://$(HOST):$(PORT)/__h5_dev_server__/health" >/dev/null 2>&1; then \
			break; \
		fi; \
		sleep 0.2; \
	done; \
	if ! curl -fsS "http://$(HOST):$(PORT)/__h5_dev_server__/health" | grep -q "ok"; then \
		echo "H5 dev server is not ready on http://$(HOST):$(PORT)/"; \
		exit 1; \
	fi; \
	open "$$URL"; \
	wait $$SERVER_PID
