GODEPS := $(shell git ls-files '*.go' go.mod go.sum)

VSN ?= $(shell git describe --dirty)
VSNHASH ?= $(shell git rev-parse --verify HEAD)
LDFLAGS ?= -ldflags "-X main.Version=$(VSN) -X main.VersionHash=$(VSNHASH)"

undocker: $(GODEPS) ## builds binary for the current architecture
	go build $(LDFLAGS) -o $@

.PHONY: test
test: coverage.out

.PHONY: lint
lint:
	go vet ./...
	staticcheck -f stylish ./...
	shellcheck $$(awk '/#!\/usr\/bin\/env (ba)?sh/&&FNR==1{print FILENAME}' $$(git ls-files))
	shfmt -w -i 4 $$(awk '/#!\/usr\/bin\/env (ba)?sh/&&FNR==1{print FILENAME}' $$(git ls-files))
	git diff --exit-code

.INTERMEDIATE: coverage.out
coverage.out: $(GODEPS)
	go test -race -cover -coverprofile $@ ./...

coverage.html: coverage.out
	go tool cover -html=$< -o $@

.PHONY: clean
clean:
	rm -f undocker coverage.html

TAR ?= $(shell command -v gtar 2>/dev/null || echo tar)

.PHONY: test-integration
test-integration: undocker
	@failed=0; \
	for img in t/*.tar; do \
		name=$$(basename "$$img" .tar); \
		TZ=UTC ./undocker "$$img" - | $(TAR) -tv > "t/$$name-got.txt"; \
		if diff -u "t/$$name.txt" "t/$$name-got.txt"; then \
			echo "$$name success"; \
		else \
			failed=1; \
		fi; \
	done; \
	exit $$failed
