PREFIX  = /usr/local
BIN_DIR = $(PREFIX)/bin
MANDIR  = $(PREFIX)/share/man
MAN8DIR = $(MANDIR)/man8

APP_NAME = $(notdir $(CURDIR))

MANPAGE = $(APP_NAME).8

GO      = go
RM      = /bin/rm --recursive --force
MOD     = go.mod
SUM     = go.sum
INSTALL = /bin/install
TOUCH   = /bin/touch
MKDIR   = /bin/mkdir --parents
MAKE    = /usr/bin/make --no-print-directory

GO_FILES   = $(shell find . -name '*.go')
COVER_FILE = coverage.out
TEST_LOG   = test.log

$(APP_NAME): $(GO_FILES) $(SUM) | $(MOD)
	$(GO) build -o $(APP_NAME) cmd/main.go

all: $(APP_NAME) doc

$(MOD):
	$(GO) mod init gitlab.com/M0M097/$(APP_NAME)

$(SUM): $(GO_FILES) | $(MOD)
	$(GO) mod tidy
	$(TOUCH) $@

clean:
	$(RM) $(APP_NAME) $(COVER_FILE) $(TEST_LOG)

run: $(APP_NAME)
	./$<

# Requires go from the `google-go-lang` package
$(COVER_FILE): $(GO_FILES) $(SUM) | $(MOD)
	$(GO) test -coverprofile=$@ ./...

# Requires go from the `google-go-lang` package
cover: $(COVER_FILE)
	$(GO) tool cover -html=$<

# Requires go from the `google-go-lang` package
vet: $(GO_FILES) $(SUM) | $(MOD)
	$(GO) vet ./...

test: $(TEST_LOG)

$(TEST_LOG): $(GO_FILES) | $(MOD)
	$(GO) test -vet=off ./... | tee $@

fmt:
	$(GO) fmt ./...

install: $(APP_NAME) | $(BIN_DIR)/ $(MAN8DIR)/
	$(INSTALL) --mode=0755 --strip $< $(BIN_DIR)
	$(INSTALL) --mode=0644 $(MANPAGE) $(MAN8DIR)
	gzip -f $(MAN8DIR)/$(MANPAGE)

%/:
	$(MKDIR) $@

# If doc.mk exists, include it for documentation generation
doc: $(APP_NAME) test.log
	$(addprefix $(MAKE) APP_NAME=$< --makefile=, $(wildcard doc.mk))

.PHONY: all clean run test fmt install doc vet
