.PHONY: build build-release frontend backend run migrate reconcile reconcile-delete tidy test testdata clean

# Release version stamped into the binary (-X main.version). Override with VERSION=...
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)

# Seed testdata parameters (see `make testdata`). Counts: ALBUMS, PHOTOS, SEED, TIMEOUT.
# Boolean (set to 1 to enable): TAGS, COMMENTS, LIKES, SHARE, INVITES, WAIT, DRY, VIDEO.
# VIDEO requires ffmpeg on PATH; it is skipped without it. Extra passthrough flags: ARGS.
ALBUMS ?= 2
PHOTOS ?= 10
SEED ?= 0
TIMEOUT ?= 30

frontend:
	cd frontend && npm ci && npm run build
	rm -rf backend/static/*
	cp -r frontend/build/* backend/static/

backend:
	mkdir -p bin
	# -tags nodynamic forces gen2brain/webp to use its pure-Go transpiled path
	# (no purego/dlopen), keeping the binary fully static.
	cd backend && CGO_ENABLED=0 go build -tags nodynamic -trimpath -ldflags="-s -w" \
		-o ../bin/galo ./cmd/server

build: frontend backend

# Release build: full static, stripped and (if available) UPX-compressed binary
# with the version embedded. Produces bin/galo and a copy at bin/galo-$(VERSION).
build-release: frontend
	mkdir -p bin
	cd backend && CGO_ENABLED=0 go build -tags nodynamic -trimpath \
		-ldflags="-s -w -X main.version=$(VERSION)" -o ../bin/galo ./cmd/server
	strip --strip-all bin/galo
	@if command -v upx >/dev/null 2>&1; then \
		upx --best --quiet bin/galo && echo "upx: bin/galo compressed"; \
	else \
		echo "upx not found - skipping compression (install upx-ucl to enable)"; \
	fi
	cp bin/galo bin/galo-$(VERSION)
	@echo "release: bin/galo-$(VERSION)"

run: backend
	./bin/galo

migrate:
	cd backend && go run ./cmd/migrate

# Reconcile object storage against the metadata journal (report only).
reconcile:
	cd backend && go run ./cmd/reconcile

# Reconcile and delete orphaned blobs older than --min-age (default 1h).
# Override the grace period when needed: make reconcile-delete MIN_AGE=1m
reconcile-delete:
	cd backend && go run ./cmd/reconcile --delete $(if $(MIN_AGE),--min-age $(MIN_AGE),)

tidy:
	cd backend && go mod tidy

test:
	cd backend && go test ./...

# Seed test data into a running instance through the public API (additive only).
# Credentials come from the environment: GALO_EMAIL, GALO_PASSWORD
# (optional GALO_BASE_URL). Example:
#   make testdata ALBUMS=3 PHOTOS=5 TAGS=1 LIKES=1 SEED=42
testdata:
	@python3 scripts/seed.py \
		--albums $(ALBUMS) \
		--photos-per-album $(PHOTOS) \
		--seed $(SEED) \
		--timeout $(TIMEOUT) \
		$(if $(filter 1,$(TAGS)),--tags,) \
		$(if $(filter 1,$(COMMENTS)),--comments,) \
		$(if $(filter 1,$(LIKES)),--likes,) \
		$(if $(filter 1,$(SHARE)),--share-links,) \
		$(if $(filter 1,$(INVITES)),--invites,) \
		$(if $(filter 1,$(VIDEO)),--video,) \
		$(if $(filter 1,$(WAIT)),--wait-variants,) \
		$(if $(filter 1,$(DRY)),--dry-run,) \
		$(ARGS)

clean:
	rm -rf bin backend/static/*
	touch backend/static/.gitkeep
