export DOCKER_BUILDKIT := 1
export PROGRESS_NO_TRUNC := 1
GOPATH := $(shell go env GOPATH)
export PATH := $(PATH):$(GOPATH)/bin
PROTOC_GEN_GO := $(GOPATH)/bin/protoc-gen-go
SOURCEFILES := mfer/*.go mfer/*.proto internal/*/*.go cmd/*/*.go go.mod go.sum
ARCH := $(shell uname -m)
GITREV_BUILD := $(shell bash $(PWD)/bin/gitrev.sh)
APPNAME := mfer
VERSION := 0.1.0
export DOCKER_IMAGE_CACHE_DIR := $(HOME)/Library/Caches/Docker/$(APPNAME)-$(ARCH)
GOLDFLAGS += -X main.Version=$(VERSION)
GOLDFLAGS += -X main.Gitrev=$(GITREV_BUILD)
GOFLAGS := -ldflags "$(GOLDFLAGS)"

.PHONY: docker default run ci test fixme

default: fmt test

run: ./mfer.cmd
	./$<
	./$< gen

ci: test

test: $(SOURCEFILES) mfer/mf.pb.go
	go test -v --timeout 3s ./...

$(PROTOC_GEN_GO):
	test -e $(PROTOC_GEN_GO) || go install -v google.golang.org/protobuf/cmd/protoc-gen-go@v1.28.1

fixme:
	@grep -nir fixme . | grep -v Makefile

devprereqs:
	which golangci-lint || go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@latest

mfer/mf.pb.go: mfer/mf.proto
	cd mfer && go generate .

mfer.cmd: $(SOURCEFILES) mfer/mf.pb.go
	protoc --version
	cd cmd/mfer && go build -tags urfave_cli_no_docs -o ../../mfer.cmd $(GOFLAGS) .

clean:
	rm -rfv mfer/*.pb.go mfer.cmd cmd/mfer/mfer *.dockerimage

fmt: mfer/mf.pb.go
	gofumpt -l -w mfer internal cmd
	golangci-lint run --fix
	-prettier -w *.json
	-prettier -w *.md

lint:
	golangci-lint run
	sh -c 'test -z "$$(gofmt -l .)"'

docker: sneak-mfer.$(ARCH).tzst.dockerimage

sneak-mfer.$(ARCH).tzst.dockerimage: $(SOURCEFILES) vendor.tzst modcache.tzst
	docker build --progress plain --build-arg GITREV=$(GITREV_BUILD) -t sneak/mfer .
	docker save sneak/mfer | pv | zstdmt -19 > $@
	du -sh $@

godoc:
	open http://127.0.0.1:6060
	godoc -http=:6060

vendor.tzst: go.mod go.sum
	go mod tidy
	go mod vendor
	cd vendor && tar -c . | pv | zstdmt -19 > $(PWD)/$@.tmp
	rm -rf vendor
	mv $@.tmp $@

modcache.tzst: go.mod go.sum
	go mod tidy
	cd $(HOME)/go/pkg && chmod -R u+rw . && rm -rf mod sumdb
	go mod download -x
	cd $(shell go env GOMODCACHE) && tar -c . | pv | zstdmt -19 > $(PWD)/$@.tmp
	mv $@.tmp $@
