GIT_COMMIT ?= $(shell git rev-parse --verify HEAD)
ENVIRONMENT ?= development
MAIN_DIR ?= ./cmd/martian
GOMETALINTER_ARGS ?= --vendor --dupl-threshold=150 --min-confidence=.3 --tests --deadline=90s --disable-all \
	-Egolint -Etest -Eineffassign -Etestify -Eunconvert -Estaticcheck -Egoconst -Eerrcheck \
	-Egofmt -Evet -Edupl -Einterfacer -Estructcheck -Evetshadow -Egoimports -Evarcheck -Emisspell \
	-Emaligned -Etest --exclude=/usr/local/go/src --exclude='/mocks/[^/]+\.go.*\((dupl)|(golint)\)' \
	--exclude='' ./...
TEST_PACKAGES ?= $(shell go list ./... | grep -v /vendor/)

setup:
	go get -u golang.org/x/tools/cmd/goimports
	go get -u github.com/smartystreets/goconvey
	go get -u github.com/alecthomas/gometalinter
	gometalinter --install

precommit: fix fast_lint integration_test_cover

test:
	go test $(TEST_PACKAGES)

integration_test:
	env ENVIRONMENT=$(ENVIRONMENT) go test -race -tags=integration $(TEST_PACKAGES)

integration_test_cover:
	mkdir -p build/cover
	env ENVIRONMENT=$(ENVIRONMENT) go test -race -tags=integration -coverprofile build/cover/cover.out -coverpkg ./cmd/...,./internal/...,./client/... $(TEST_PACKAGES)
	@go tool cover -func build/cover/cover.out > build/cover/function_coverage.txt
	@# pipe to cat to swallow the error code
	@grep '\s0.0%' build/cover/function_coverage.txt | grep -v '\smain\s' | cat > build/cover/uncovered_functions.txt
	@if [ -s build/cover/uncovered_functions.txt ]; then (echo "### There are uncovered functions ###" && cat build/cover/uncovered_functions.txt && exit 1) fi;

run:
	env ENVIRONMENT=$(ENVIRONMENT) go run -race -ldflags "-X main.CodeVersion=$(GIT_COMMIT)" $(MAIN_DIR)/main.go

revendor:
	dep ensure

lint:
	gometalinter $(GOMETALINTER_ARGS)

fast_lint:
	gometalinter --fast $(GOMETALINTER_ARGS)

fix:
	find . -iname '*.go' -not -path '*/vendor/*' -print0 | xargs -0 gofmt -s -w
	find . -iname '*.go' -not -path '*/vendor/*' -print0 | xargs -0 goimports -w

mocks:
	mockery -dir ./cmd/martian/internal/api/ -all -output ./cmd/martian/internal/api/mocks

jenkins: lint test
	@# I have no idea why, but trying to get jenkins to run a build target works with local manta but fails with jenkins build agent manta...
	@# just going to bypass the whole issue and move the build command directly into the jenkins target in the makefile
	go build -ldflags "-X main.CodeVersion=$(GIT_COMMIT)" $(MAIN_DIR)
	go env
	go version
	env
	mkdir /build/service
	cp $(MAIN_DIR)/Dockerfile /build/service
	cp martian /build/service
	cp -R ./config /build/service
