VERSION ?= dev
LDFLAGS := -ldflags="-s -w -X main.version=$(VERSION)"

.PHONY: build test test-short lint fmt vet tidy run docker clean

build:
	CGO_ENABLED=0 go build $(LDFLAGS) -o bin/tomswallapi ./cmd/tomswallapi

test:
	go test ./...

# Tests that self-skip container-backed DB cases when Docker is unavailable.
test-short:
	go test -short ./...

lint: vet
	gofmt -l -d .

fmt:
	gofmt -w .

vet:
	go vet ./...

tidy:
	go mod tidy

run: build
	./bin/tomswallapi

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

clean:
	rm -rf bin

# Version-bump targets: compute the next semver tag from the latest v* tag,
# then create and push it. The v* tag triggers the docker release pipeline.
.PHONY: patch minor major
patch: ; @$(MAKE) bump PART=patch
minor: ; @$(MAKE) bump PART=minor
major: ; @$(MAKE) bump PART=major

.PHONY: bump
bump:
	@current=$$(git tag -l 'v*' --sort=-v:refname | head -1); \
	current=$${current:-v0.0.0}; \
	v=$${current#v}; \
	major=$$(echo $$v | cut -d. -f1); \
	minor=$$(echo $$v | cut -d. -f2); \
	patch=$$(echo $$v | cut -d. -f3); \
	case "$(PART)" in \
	  major) major=$$((major+1)); minor=0; patch=0;; \
	  minor) minor=$$((minor+1)); patch=0;; \
	  patch) patch=$$((patch+1));; \
	  *) echo "PART must be major|minor|patch"; exit 1;; \
	esac; \
	next="v$$major.$$minor.$$patch"; \
	echo "Tagging $$next (was $$current)"; \
	git tag -a "$$next" -m "Release $$next"; \
	git push origin "$$next"
