COMPOSE ?= docker compose
COMPOSE_DEV := $(COMPOSE) -f compose.dev.yaml
COMPOSE_PROD := $(COMPOSE) -f compose.prod.yaml

# Compose does not support nested ${VAR:-${HOME}/...}; set host cache paths here (override in .env).
-include .env
HOST_GOMODCACHE := $(if $(strip $(GOMODCACHE)),$(strip $(GOMODCACHE)),$(HOME)/go/pkg/mod)
HOST_GOCACHE := $(if $(strip $(GOCACHE)),$(strip $(GOCACHE)),$(HOME)/.cache/go-build)
export HOST_GOMODCACHE HOST_GOCACHE

DEV_ENV := env HOST_GOMODCACHE="$(HOST_GOMODCACHE)" HOST_GOCACHE="$(HOST_GOCACHE)"
DEV_RUN := $(DEV_ENV) $(COMPOSE_DEV) run --rm --no-deps -T dev

.PHONY: dev build up down generate tidy logs thumbs sync-media publish convert-videos

.DEFAULT_GOAL := dev

dev:
	@test -f .env || cp -n .env.example .env
	@if [ "$$(id -u)" = "0" ]; then \
		echo "Do not run 'sudo make dev' — it creates root-owned files under app/ and breaks rootless Docker."; \
		echo "Run: make dev"; \
		exit 1; \
	fi
	$(DEV_ENV) $(COMPOSE_DEV) up --build dev

build:
	$(COMPOSE_PROD) build website

up:
	@test -f .env || cp -n .env.example .env
	$(COMPOSE_PROD) up --build website

down:
	-$(COMPOSE_DEV) down
	-$(COMPOSE_PROD) down

generate:
	$(DEV_RUN) sh -c "templ generate"

tidy:
	$(DEV_RUN) go mod tidy

logs:
	$(COMPOSE_DEV) logs -f dev

# Pre-build gallery thumbnails and video poster JPEGs (ffmpeg in dev image).
thumbs:
	$(DEV_RUN) go run ./cmd/server -thumbs

# Copy photos and convert videos from upload/ into app/images/.
sync-media:
	$(DEV_RUN) sh -c 'UPLOAD_DIR=/upload IMAGES_DIR=/app/images ./scripts/sync-media.sh $(ARGS)'

# sync-media then rebuild thumbs/hero derivatives under app/images/.
publish: sync-media thumbs

# Alias for sync-media (videos are converted as part of sync).
convert-videos: sync-media
