# distribution — build/test gate.
#
# The sx compiler lives in a separate repo; locate it via SX (overridable):
#   make build SX=/path/to/sx
SX ?= /Users/agra/projects/sx/zig-out/bin/sx

BUILD_DIR := build

# Programs compiled by `make build`: the smoke program and the `dist`
# product entry point. Further entry points under src/ get added here as
# they land.
#
# SQLite ships with sx itself (its library's vendors/sqlite module,
# imported as `vendors/sqlite/sqlite.sx`): a named `#import c` unit the
# compiler builds through its content-addressed object cache
# (.sx-cache/) — once per machine. `sx build` links the unit's objects
# into the binary; `sx run` loads them as a priority symbol target the
# OS libsqlite3 cannot shadow. Nothing SQLite-related lives in this
# repo anymore.
SMOKE := tests/smoke.sx
DIST  := src/dist.sx

.PHONY: build test publish-example lan clean

# Compile the product sources (and the smoke program) without running.
build:
	@mkdir -p $(BUILD_DIR)
	$(SX) build -o $(BUILD_DIR)/smoke $(SMOKE)
	$(SX) build -o $(BUILD_DIR)/dist $(DIST)

# Run the test runner over every tests/**/*.sx. Exits non-zero on any
# failure. Depends on `build` so the CLI acceptance test (tests/cli_*.sx)
# finds a fresh `build/dist` to drive.
test: build
	@SX="$(SX)" ./tests/run.sh

# End-to-end local publish of examples/dist.json into a fresh .sx-tmp/
# store, emitting the machine-readable JSON result on stdout. Depends on
# `build` so build/dist exists; the store is reset first so re-runs don't
# collide on the release id.
publish-example: build
	@rm -rf .sx-tmp/publish-example
	./$(BUILD_DIR)/dist ci publish --manifest examples/dist.json --local-store .sx-tmp/publish-example --json

# Serve the persistent .lan/ store on 0.0.0.0:$(LAN_PORT) for LAN access.
# Rebuilds first and REPLACES any running instance, so the served binary
# is always the current tree. Detached via nohup; log lives with the
# store's other state (one data dir, like the /data volume in PLAN.md).
LAN_PORT  ?= 8787
LAN_STORE ?= .lan

lan: build
	@pkill -f "dist server run --local-store $(LAN_STORE)" 2>/dev/null || true
	@lsof -tiTCP:$(LAN_PORT) -sTCP:LISTEN | xargs kill 2>/dev/null || true; sleep 0.3
	@mkdir -p $(LAN_STORE)
	@sh -c 'nohup ./$(BUILD_DIR)/dist server run --local-store $(LAN_STORE) --port $(LAN_PORT) >> $(LAN_STORE)/distd.log 2>&1 & echo "distd pid $$!"'
	@echo "admin:  http://$$(ipconfig getifaddr en0 2>/dev/null || echo localhost):$(LAN_PORT)/admin"

clean:
	@rm -rf $(BUILD_DIR) .sx-cache
