NAMESPACE ?= golang
PACKAGE := bumpversion
SHELL := /bin/bash
REGISTRY := registry.halfakop.ru
REPOSITORY := $(NAMESPACE)/$(PACKAGE)
PLATFORM ?= --platform=linux/amd64
GOCACHE ?= $(CURDIR)/.cache/go-build

SOURCE_VERSION ?= $(shell cat VERSION)
SOURCE_COMMIT ?= $(shell git rev-parse --short=8 HEAD)
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD | sed s,feature/,,g)
LDFLAGS := -X main.AppVersion=$(SOURCE_VERSION) -X main.AppCommit=$(SOURCE_COMMIT)

IMAGE_NAME_TAGGED = $(REPOSITORY):$(SOURCE_VERSION)
EXEC=$(PACKAGE).run

all: help

help:
	@printf "\nMain make targets:\n"
	@printf "  make app              - Download deps, fix, build app (binary: %s)\n" "$(EXEC)"
	@printf "  make test             - Run unit tests\n"
	@printf "  make test-integration - Run tests that require Postgres (testcontainers)\n"
	@printf "  make run              - Build then run locally\n"
	@printf "  make clean    - Clean build artifacts\n"
	@printf "  make release  - Clean, build image, login, push\n"
	@printf "\nVariables:\n"
	@printf "  NAMESPACE=%s\n" "$(NAMESPACE)"
	@printf "  PACKAGE=%s\n" "$(PACKAGE)"
	@printf "  IMAGE_NAME_TAGGED=%s\n" "$(IMAGE_NAME_TAGGED)"
	@printf "  EXEC=%s\n\n" "$(EXEC)"

download:
	@echo "Download dependencies"
	@GOCACHE=$(GOCACHE) go mod download

fix:
	@echo "Fix code"
	@GOCACHE=$(GOCACHE) go fix ./...

app: download fix
	@echo "Build application"
	@GOCACHE=$(GOCACHE) go build -ldflags "$(LDFLAGS)" -o ./${EXEC} ./src

tests: app
	@echo "Run tests"
	@GOCACHE=$(GOCACHE) go test ./...

test:
	@echo "Run unit tests"
	@GOCACHE=$(GOCACHE) go test -count=1 ./...

test-integration:
	@echo "Run integration tests (requires Docker for Postgres)"
	@GOCACHE=$(GOCACHE) go test -tags=integration -count=1 ./...

run:
	@echo "Run application"
	@./${EXEC}

clean:
	@echo "Clean build environment"
	@rm -rf ./${EXEC}% $(GOCACHE)

release: clean build login push

build:
	DOCKER_BUILDKIT=0 \
	docker build $(PLATFORM) --progress=plain --compress \
		-t $(IMAGE_NAME_TAGGED) \
		-t $(REGISTRY)/$(IMAGE_NAME_TAGGED) \
		--build-arg SOURCE_VERSION=$(SOURCE_VERSION) \
		--build-arg SOURCE_COMMIT=$(SOURCE_COMMIT) \
		--build-arg GOPROXY=$(GOPROXY) \
		--build-arg GONOSUMDB=$(GONOSUMDB) \
		${DOCKER_OPTS} \
		-f Dockerfile .

login:
	$(call check-var-defined,DOCKER_USERNAME)
	$(call check-var-defined,DOCKER_PASSWORD)
	@echo ${DOCKER_PASSWORD} | \
	docker login -u ${DOCKER_USERNAME} --password-stdin $(REGISTRY)

push:
	docker push $(REGISTRY)/$(IMAGE_NAME_TAGGED)

.PHONY: tests test test-integration release build login push download fix app clean run help
