VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
LDFLAGS := -s -w -X main.version=$(VERSION)
BIN     := docker-migrate
OUT     := dist

# PowerShell 7+. The publish path lives in scripts/*.ps1 because uploading a
# Gitea release asset needs an HTTP client, not a shell loop.
PWSH ?= pwsh
# Extra flags forwarded to publish.ps1, e.g. `make publish ARGS=-Force`.
ARGS ?=

.PHONY: all ui build run test vet fmt docker clean release publish publish-binaries help

help:
	@echo "make ui                build the web interface into internal/webui/dist"
	@echo "make build             build the binary for this platform (implies ui)"
	@echo "make run               build and start the server on 127.0.0.1:8080"
	@echo "make test              run the Go tests"
	@echo "make docker            build the container image"
	@echo "make release           cross-compile linux/amd64, linux/arm64, darwin/arm64, windows/amd64"
	@echo "make publish           push the image to git.azuze.fr and attach binaries to the release"
	@echo "make publish-binaries  binaries only: no docker build, login or push"

all: build

ui:
	cd web && npm ci --no-audit --no-fund && npm run build

build: ui
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BIN) .

# Build without rebuilding the UI, for a quick backend iteration.
build-go:
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BIN) .

run: build
	./$(BIN) serve --addr 127.0.0.1:8080 -v

test:
	go test ./...

vet:
	go vet ./...

fmt:
	go fmt ./...
	cd web && npx tsc -b --noEmit

docker:
	docker build --build-arg VERSION=$(VERSION) -t docker-migrate:$(VERSION) -t docker-migrate:latest .

release: ui
	@mkdir -p $(OUT)
	@set -e; for target in linux/amd64 linux/arm64 darwin/arm64 darwin/amd64 windows/amd64; do \
	  os=$${target%/*}; arch=$${target#*/}; \
	  ext=""; [ "$$os" = "windows" ] && ext=".exe"; \
	  echo "building $$os/$$arch"; \
	  CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath -ldflags "$(LDFLAGS)" \
	    -o $(OUT)/$(BIN)-$$os-$$arch$$ext .; \
	done
	@ls -lh $(OUT)

# Needs GITEA_USER + GITEA_TOKEN in the environment, or it prompts. The token
# needs package read/write for the push and write:repository for the release.
publish:
	$(PWSH) -NoProfile -ExecutionPolicy Bypass -File scripts/publish.ps1 \
	  -Tag $(VERSION) -PublishRelease $(ARGS)

publish-binaries:
	$(PWSH) -NoProfile -ExecutionPolicy Bypass -File scripts/publish.ps1 \
	  -Tag $(VERSION) -BinariesOnly $(ARGS)

clean:
	rm -rf $(BIN) $(BIN).exe $(OUT) internal/webui/dist/assets
	rm -rf web/node_modules
