.PHONY: setup build test lint generate cover fmt e2e-test-only build-artifact update_credentials run_prod run_staging ci ci-e2e

GIT_COMMIT=$(shell git rev-parse HEAD)
IMAGE=docker-registry.internal.justin.tv/insights/piper-service:${GIT_COMMIT}
GO111MODULE=auto

define findtool
	@which $(1) || (echo "install $(1)" && exit 1)
endef

define ci
	docker run \
		--rm \
		-e AWS_ACCESS_KEY_ID=$$AWS_ACCESS_KEY_ID \
		-e AWS_SECRET_ACCESS_KEY=$$AWS_SECRET_ACCESS_KEY \
		-e AWS_SESSION_TOKEN=$$AWS_SESSION_TOKEN \
		-v $$PWD:/build/go/src/code.justin.tv/insights/piper-service:delegated \
		-w /build/go/src/code.justin.tv/insights/piper-service \
		docker.internal.justin.tv/devtools/xenial/go1.13.3:latest \
		$(1)
endef

run_staging:
	go run cmd/run/main.go staging

run_prod:
	go run cmd/run/main.go prod

setup:
	$(call findtool, go)
	# if retool is not available, install it to GOBIN using source files
	# in retool directory. this makes retool available for use
	which retool || GOBIN=$$GOPATH/bin GOPATH=$$PWD/_tools go install github.com/twitchtv/retool
	# ensure tools are installed before using them
	retool build
	retool do gometalinter --install

update_credentials:
	$(call findtool, mwinit)
	$(call findtool, ada)
	ada credentials update --once --account=895328872748 --provider=isengard --role=Admin --profile=twitch-service-piper-dev
	ada credentials update --once --account=452744562037 --provider=isengard --role=Admin --profile=twitch-service-piper-aws

ci:
	$(call ci, make ci-no-integration-test)

codecoverage:
	./scripts/codecoverage.sh

build-artifact:
	mkdir -p ./artifact/
	cp -R deploy/. artifact/
	cp coverage.xml artifact/
	go build -o ./artifact/piper-service

ci-no-integration-test: lint codecoverage build-artifact

integrate-test: lint codecoverage build-artifact
	./scripts/integrate.sh

e2e-test-only: build-artifact
	./scripts/integrate.sh

ci-e2e:
	$(call ci, make e2e-test-only)

docker-build-push:
	docker build -t ${IMAGE} .
	docker push ${IMAGE}

lint: setup
	go vet ./...
	retool do errcheck -blank ./...
	retool do gometalinter --disable-all --vendor --tests --deadline=5m --enable=gofmt --enable=goimports ./...
	retool do nicer ./...

test:
	go test ./...

fmt: setup
	go fmt ./...
	goimports -w api backend internal lib tools models client main.go

generate:
	go generate ./...

cover:
	./scripts/coverage.sh
	go tool cover -html=coverage.out
