# -*- mode: makefile -*-
SHELL := /bin/bash
PREFIX?=$(shell pwd)

# Setup name variables for the package/tool
PROJECTNAME := pdns-auth-proxy

# Set our default go compiler
GO := go

VERSION := $(shell git describe --tags)
GITCOMMIT := $(shell git rev-parse --short HEAD)
PKG := git.euclide.org/euclide/$(PROJECTNAME)

CTIMEVAR=-X $(PKG)/version.GITCOMMIT=$(GITCOMMIT) -X $(PKG)/version.VERSION=$(VERSION)
GO_LDFLAGS=-ldflags "-w $(CTIMEVAR)"
GO_LDFLAGS_STATIC=-ldflags "-w $(CTIMEVAR) -extldflags -static"
GOCACHE=off

BUILDDIR := ${PREFIX}/build
DOCKER_IMAGE := $(docker images --format "{{.Repository}}" --filter=reference='$(PROJECTNAME):$(GITCOMMIT)')
GOOSARCHES := linux/amd64

all: build fmt test

.PHONY: fmt
fmt: ## Verifies all files have been `gofmt`ed.
	@echo "+ $@"
	$(eval var = $(shell gofmt -s -l . | grep -v vendor | tee /dev/stderr))
	@if [ ! -z "${var}" ]; then exit 1; fi
	$(MAKE) -C client fmt

.PHONY: tag
tag: ## Create a new git tag to prepare to build a release
	git tag -sa $(VERSION) -m "$(VERSION)"
	@echo "Run git push origin $(VERSION) to push your new tag to GitHub and trigger a Jenkins build."

.PHONY: test
test: ## Generates test certificates & run unit tests.
	$(MAKE) -C fixtures/test
	go vet
	go test -v -coverprofile=coverage.out
	$(MAKE) -C client test

.PHONY: resetreplay
resetreplay:
	rm -f fixtures/replay/record
	$(MAKE) clean
	$(MAKE) test

.PHONY: deb
deb:
	debuild -e GOROOT -e PATH -i -us -uc -b

.PHONY: build
build: ## Builds a static executable.
	@echo "+ $@"
	CGO_ENABLED=0 $(GO) build \
	 -o $(PROJECTNAME) \
	 -tags "static_build netgo" \
	 -trimpath \
	 -installsuffix netgo ${GO_LDFLAGS_STATIC} .;
	strip $(PROJECTNAME) 2>/dev/null || echo
	$(MAKE) -C client build

.PHONY: vendor
vendor: ## Updates the vendoring directory.
	# @$(RM) go.sum
	@$(RM) -r vendor
	GOPRIVATE=git.euclide.org $(GO) mod init $(PKG) || true
	GOPRIVATE=git.euclide.org $(GO) mod tidy
	GOPRIVATE=git.euclide.org $(GO) mod vendor
	@$(RM) Gopkg.toml Gopkg.lock

.PHONY: clean
clean: ## Cleanup any build binaries or packages.
	@echo "+ $@"
	$(RM) $(PROJECTNAME) debug
	$(RM) -r $(BUILDDIR)
	$(MAKE) -C fixtures/test clean
	$(MAKE) -C client clean
