-include environ.inc

export CGO_ENABLED=0
VERSION ?= $(shell git describe --abbrev=0 --tags 2>/dev/null)
COMMIT ?= $(shell git rev-parse --short HEAD)
BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
BUILD ?= $(shell git show -s --pretty=format:%cI)
GOCMD=go

DESTDIR=/usr/local/bin

ifeq ($(LOCAL), 1)
IMAGE := r.mills.io/prologic/pages-server
TAG := dev
else
ifeq ($(BRANCH), main)
IMAGE := prologic/pages-server
TAG := latest
else
IMAGE := prologic/pages-server
TAG := dev
endif
endif

ifndef $$VERSION
VERSION := "0.0.0"
endif

all: help

.PHONY: help
help: ## Show this help message
	@echo "pages-server - a Self-Hosted Pages Server for Gitea"
	@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n  make \033[36m\033[0m\n"} /^[$$()% a-zA-Z_-]+:.*?##/ { printf "  \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)

.PHONY: dev
dev : DEBUG=1
dev : build ## Build debug version of pages-server (server)
	@./pages-server -D

.PHONY: build
build: ## Build the pages-server binary (server)
ifeq ($(DEBUG), 1)
	@echo "Building in debug mode..."
	@$(GOCMD) build $(FLAGS) -tags "netgo static_build" -installsuffix netgo \
		.
else
	@$(GOCMD) build $(FLAGS) -tags "netgo static_build" -installsuffix netgo \
		.
endif

.PHONY: install
install: build ## Install pages-server (server) to $DESTDIR
	@install -D -m 755 pages-server $(DESTDIR)/pages-server

ifeq ($(PUBLISH), 1)
.PHONY: image
image: generate ## Build the Docker image
	@docker buildx build \
		--platform linux/amd64,linux/arm64 --push -t $(IMAGE):$(TAG) .
else
.PHONY: image
image: generate
	@docker build  \
		-t $(IMAGE):$(TAG) .
endif

.PHONY: fmt
fmt: ## Format sources files
	@$(GOCMD) fmt ./...

.PHONY: test
test: ## Run test suite
	@CGO_ENABLED=1 $(GOCMD) test -v -cover -race ./...

.PHONY: coverage
coverage: ## Get test coverage report
	@CGO_ENABLED=1 $(GOCMD) test -v -cover -race -cover -coverprofile=coverage.out  ./...
	@$(GOCMD) tool cover -html=coverage.out

.PHONY: clean
clean: ## Remove untracked files
	@git clean -f -d -x

.PHONY: clean-all
clean-all:  ## Remove untracked and Git ignored files
	@git clean -f -d -X
