CARGO ?= $(HOME)/.cargo/bin/cargo
PORT  ?= 8000

.DEFAULT_GOAL := run
.PHONY: run build start clean push pull migrate

# Dev: Vite watch + cargo run concurrently. Both die on Ctrl+C.
# Lighthouse runs in-process (subprocess to node_modules/.bin/lighthouse via
# `bun run --bun`), so the dev binary needs the root bun install too.
run: frontend/node_modules dist/.vite/manifest.json node_modules
	@trap 'kill 0' EXIT INT TERM; \
	(cd frontend && bun run dev) & \
	PORT=$(PORT) $(CARGO) run

# Production build (Vite assets + release binary)
build: frontend/node_modules
	cd frontend && bun run build
	$(CARGO) build --release

# Run the release binary (after `make build`)
start:
	PORT=$(PORT) ./target/release/status

# Nuke everything regenerable: build output, deps (frontend + lighthouse), and
# the local data dir (sqlite + WAL/SHM — re-fetch with `make pull`).
clean:
	rm -rf target dist frontend/node_modules node_modules data

push:
	git remote | xargs -I R git push R master

# Import an existing Django status SQLite into the rust schema.
# `make migrate FROM=../status-django/db.sqlite3` (add FORCE=1 to wipe first).
migrate:
	@if [ -z "$(FROM)" ]; then echo "usage: make migrate FROM=<path-to-django.sqlite3> [FORCE=1]"; exit 2; fi
	$(CARGO) run -- migrate "$(FROM)" $(if $(FORCE),--force,)

# Pull production data (db, media) for local dev
pull:
	@SERVER=$$(git config --get remote.server.url | sed 's|ssh://||' | cut -d ':' -f 1 | cut -d '/' -f 1); \
	NAME=$$(basename $$(pwd)); \
	mkdir -p data; \
	rsync -avz $$SERVER:/srv/data/$$NAME/db/db.sqlite3 data/db.sqlite3

frontend/node_modules:
	cd frontend && bun install

# Lighthouse package, installed at the repo root because the lighthouse binary
# lives at node_modules/.bin/lighthouse and reads node_modules/lighthouse at
# runtime. Installed with bun (no nodejs/npm in the runtime image).
node_modules: package.json
	bun install --production

dist/.vite/manifest.json: frontend/node_modules
	cd frontend && bun run build
