BINARY       := agent-sandbox
DIST         := dist
IMAGE        := localhost/agent-sandbox:dev
ROUTER_IMAGE := localhost/agent-sandbox-router:dev
# dev runs the local :dev images; a release tag pins the published images.
VERSION      ?= dev
GOFLAGS      := -ldflags="-s -w -X main.version=$(VERSION)"
# podman-remote's build tags: the API bindings without cgo storage drivers.
TAGS         := remote,exclude_graphdriver_btrfs,containers_image_openpgp
OS           ?= $(shell go env GOOS)
ARCH         ?= $(shell go env GOARCH)

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

all: build

build: bin images

bin:
	CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build -tags $(TAGS) $(GOFLAGS) -o $(DIST)/$(BINARY) .

images:
	podman build --format docker -t $(IMAGE) .
	podman build --format docker -t $(ROUTER_IMAGE) router

test:
	go test -tags $(TAGS) -v -race ./...

vet:
	go vet -tags $(TAGS) ./...

lint:
	golangci-lint run ./...

fmt:
	gofmt -w .

pre-commit:
	@uvx pre-commit run --all-files

clean:
	rm -rf $(DIST)

# Build the binary then package it into an RPM via nfpm.
rpm: bin rpm-package

# Package an already-built binary into an RPM (used by CI after the build step).
rpm-package:
	./scripts/build-rpm.sh $(VERSION)

# Bump helpers — reads the latest semver tag and creates the next one.
# If no tag exists yet, starts from v0.0.0.
_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)
