PROJECT_NAME := cpu_ctrl
PKG := "amuz.es/src/infra/$(PROJECT_NAME)"
PKG_LIST := $(shell go list ${PKG}/... | grep -v /vendor/)
GO_FILES := $(shell find . -name '*.go' | grep -v /vendor/ | grep -v _test.go)
BUILD=`date +%FT%T%z`
IS_DIRTY=$(shell sh -c '[[ `git diff --shortstat 2> /dev/null | tail -n1` != "" ]] && echo "-dirty"')
VERSION?=$(shell git describe --exact-match 2> /dev/null || echo "`git symbolic-ref HEAD 2> /dev/null | cut -b 12-`-`git log --pretty=format:\"%h\" -1`")$(IS_DIRTY)
DIST_NAME:= $(PROJECT_NAME).cpio.gz
UTILS :=$(shell find cmd -type d -maxdepth 1 -mindepth 1|sed -e 's/cmd\///g')

.PHONY: all vgo build

all: build

lint: ## Lint the files
	@golint -set_exit_status ${PKG_LIST}

test: ## Run unittests
	@go test -short ${PKG_LIST}

race: vgo ## Run data race detector
	@go test -race -short ${PKG_LIST}

msan: vgo ## Run memory sanitizer
	@go test -msan -short ${PKG_LIST}

vgo.lock: ## Get the dependencies
	@echo -n ensure 'vgo' dependency resolver..
	@go get -u golang.org/x/vgo
	@echo done
	@echo -n resolving dependencies..
	@${GOPATH}/bin/vgo mod -fix -vendor -sync
	@echo done
	@touch vgo.lock

vgo: vgo.lock

build: vgo ## Build the binary file
	@echo -n building..
	@go build -ldflags "-w -s -X main.version=${VERSION} -X main.buildDate=${BUILD}" -o "${PROJECT_NAME}" .
	@echo done

build_util: vgo ## Build the binary file
	@echo building..
	@$(foreach UTIL,$(UTILS),printf "=> $(UTIL):" ;\
	go build -ldflags "-w -s -X main.version=${VERSION} -X main.buildDate=${BUILD}"  -o "cmd/$(UTIL)/$(UTIL)" $(PKG)/cmd/$(UTIL) ;\
	echo done ;)
	@echo done

clean: ## Remove previous build
	@$(foreach UTIL,$(UTILS),rm -f "cmd/$(UTIL)/$(UTIL)";)
	@rm -f "$(PROJECT_NAME)"
	@rm -rf build

version: ## Display version
	@echo $(VERSION)

help: ## Display this help screen
	@grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

dist: build build_util
	@rm -rf build
	@mkdir -p build
	@mv -f "$(PROJECT_NAME)" "build/$(PROJECT_NAME)"
	@$(foreach UTIL,$(UTILS),mv -f "cmd/$(UTIL)/$(UTIL)" "build/$(UTIL)";)
	@echo  -n archieving..
	@pushd build 1> /dev/null 2>&1;find . -mindepth 1 ! -name $(DIST_NAME) | cpio --quiet -o |gzip > $(DIST_NAME) ;popd 1>/dev/null 2>&1
	@echo " build/$(DIST_NAME)"
