PORT ?= 8080
HOST ?= 127.0.0.1
TUNNEL_NAME ?= guitar-tabs
TUNNEL_HOST ?= tabs.bhakat.dev
TUNNEL_ORIGIN ?= http://127.0.0.1:$(PORT)
TUNNEL_EDGE_IP_VERSION ?= auto
.DEFAULT_GOAL := serve

.PHONY: help serve start tunnel-setup tunnel

help:
	@printf '%s\n' \
		'Guitar tabs sample' \
		'' \
		'Targets:' \
		'  make             Start the local server' \
		'  make serve         Start the local server' \
		'  make start         Alias for make serve' \
		'  make tunnel-setup  Create the Cloudflare Tunnel and DNS route (run once)' \
		'  make tunnel        Serve locally and run the Cloudflare Tunnel in the foreground' \
		'  make help          Show this help' \
		'' \
		'Options:' \
		'  PORT=8080                          Server port' \
		'  HOST=127.0.0.1                     Bind address' \
		'  TUNNEL_NAME=guitar-tabs            Cloudflare Tunnel name' \
		'  TUNNEL_HOST=tabs.bhakat.dev        Public hostname' \
		'  TUNNEL_ORIGIN=http://127.0.0.1:8080 Local URL served through the tunnel' \
		'  TUNNEL_EDGE_IP_VERSION=auto         Cloudflare edge IP version (auto, 4, or 6)' \
		'' \
		'Examples:' \
		'  make serve PORT=9000 HOST=0.0.0.0' \
		'  make tunnel-setup' \
		'  make tunnel TUNNEL_EDGE_IP_VERSION=4'

serve:
	uv run python -m http.server $(PORT) --bind $(HOST)

start: serve

tunnel-setup:
	cloudflared tunnel create "$(TUNNEL_NAME)"
	cloudflared tunnel route dns "$(TUNNEL_NAME)" "$(TUNNEL_HOST)"

tunnel:
	@set -e; \
		server_pid=''; \
		cleanup() { \
			if [ -n "$$server_pid" ]; then \
				kill "$$server_pid" 2>/dev/null || true; \
				wait "$$server_pid" 2>/dev/null || true; \
			fi; \
		}; \
		trap cleanup EXIT; \
		trap 'exit 130' INT TERM; \
		uv run python -m http.server "$(PORT)" --bind "$(HOST)" & \
		server_pid=$$!; \
		printf '%s\n' "Serving $(TUNNEL_ORIGIN) at https://$(TUNNEL_HOST)"; \
		cloudflared tunnel --edge-ip-version "$(TUNNEL_EDGE_IP_VERSION)" run --url "$(TUNNEL_ORIGIN)" "$(TUNNEL_NAME)"
