# simplegit build rules.
#
# pkgs/simplegit is a standalone Go module (the minimal git hosting server, plus
# its web console and the OpenAPI-driven mgmt API the console talks to). This
# Makefile is the module's self-contained entry point for building, testing, and
# regenerating its OpenAPI-driven mgmt API. Run from here as `make <target>`.

GOFLAGS := -trimpath

.PHONY: build test clean proto proto-tools proto-check

# build the simplegit server into ./build.
build:
	go build $(GOFLAGS) -o simplegit ./cmd

# run all tests.
test:
	go test ./...

# ---- Connect (crpc) contract for gitrpc ----
# gitrpc/gitrpc.proto is the single source of truth for the gitrpc method set
# -- a typed replacement for the hand-written JSON-RPC handlers in
# gitrpc/handlers.go. `make proto` regenerates the Go server/client stubs
# (connect-go) and TS client (protoc-gen-es). Generated files live under
# gitrpc/v1/ and are committed; a normal build does not run this.
# Requires `protoc` on PATH (brew install protobuf).
PROTO     := gitrpc/gitrpc.proto
PROTOV1   := gitrpc/v1
GOPATHBIN := $(shell go env GOPATH)/bin
WEBROOT   := ../../web

# proto-tools installs the protoc plugins once: Go (protoc-gen-go +
# protoc-gen-connect-go via `go install`) and TS (protoc-gen-es via web's bun),
# plus the Go runtime deps the generated code imports. Run before the first
# `make proto`. Pin the @versions for reproducible CI.
.PHONY: proto-tools
proto-tools:
	go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
	go install connectrpc.com/connect/cmd/protoc-gen-connect-go@latest
	go get connectrpc.com/connect@latest google.golang.org/protobuf@latest
	cd $(WEBROOT) && bun add -d @bufbuild/protoc-gen-es @bufbuild/protobuf @connectrpc/connect

# proto regenerates Go (gitrpc/v1/gitrpc.pb.go messages + gitrpc/v1/v1connect/
# gitrpc.connect.go service client) and TS (gitrpc/v1/ts/gitrpc_pb.ts) from
# $(PROTO). module=simplegit strips the module prefix from go_package so Go
# output lands in gitrpc/v1/ (not simplegit/gitrpc/v1).
.PHONY: proto
proto-go:
	protoc -I . \
		--go_out=. --go_opt=module=simplegit \
		--connect-go_out=. --connect-go_opt=module=simplegit \
		--plugin=protoc-gen-go=$(GOPATHBIN)/protoc-gen-go \
		--plugin=protoc-gen-connect-go=$(GOPATHBIN)/protoc-gen-connect-go \
		$(PROTO)

proto-ts:
	mkdir -p $(PROTOV1)/ts
	PATH="$(WEBROOT)/node_modules/.bin:$$PATH" protoc -I . \
		--es_out=$(PROTOV1)/ts \
		--es_opt=target=ts $(PROTO)

proto: proto-go proto-ts

# proto-check regenerates in place and fails if a generated file drifted (CI).
.PHONY: proto-check
proto-check: proto
	@git diff --exit-code -- $(PROTOV1) && echo "proto: generated files up to date"
