DIST     := dist
VERSION  := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
GOFLAGS  := -ldflags="-s -w -X main.version=$(VERSION)"
OS       ?= $(shell go env GOOS)
ARCH     ?= $(shell go env GOARCH)

REGISTRY := artifactapi.k8s.syd1.au.unkin.net/docker-internal

# Shipped binaries; each has its own main package under cmd/.
BINARIES := mediamark

.PHONY: all build test vet fmt lint clean images patch minor major _tag pre-commit run

all: build

# Mirror the .woodpecker/pre-commit.yaml checks locally.
pre-commit:
	test -z "$$(gofmt -l .)"
	go vet ./...

build:
	@for b in $(BINARIES); do \
		echo "building $$b"; \
		CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GOFLAGS) -o $(DIST)/$$b ./cmd/$$b || exit 1; \
	done

test:
	go test -race -count=1 ./...

vet:
	go vet ./...

fmt:
	gofmt -w .

lint:
	golangci-lint run ./...

clean:
	rm -rf $(DIST)

# Local convenience: build the container image.
images:
	docker build --build-arg VERSION=$(VERSION) -t $(REGISTRY)/mediamark:$(VERSION) .

# Local convenience: serve against a scratch media tree with no *arr backends.
run: build
	MEDIAMARK_MEDIA_ROOT=$(PWD)/testdata/media $(DIST)/mediamark

# Bump helpers — read the latest semver tag and create the next one. CI builds
# and pushes the image on the resulting v* tag.
_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1)
_BASE   := $(if $(_LATEST),$(_LATEST),v0.0.0)
_MAJ    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1)
_MIN    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2)
_PAT    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3)

patch:
	@NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

minor:
	@NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

major:
	@NEW=v$(shell expr $(_MAJ) + 1).0.0; \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

_tag:
	git push origin $(TAG)
