git_sha := $(shell [ -d ".git" ] && git rev-parse --short HEAD || echo "unknown")
docker_build_image := docker.internal.justin.tv/devtools/bionic/go1.12.1:latest
date := $(shell date -u +"%FT%H%MZ")

# Determine which S3 bucket, and lambda.
LAMBDA_ARN=$(shell aws resourcegroupstaggingapi get-resources --tag-filters Key=DeployLambda,Values=TagsValidator | jq -r ".ResourceTagMappingList[0].ResourceARN")
BUCKET_ARN=$(shell aws resourcegroupstaggingapi get-resources --tag-filters Key=DeployBucket,Values=TagsValidator | jq -r '.ResourceTagMappingList[0].ResourceARN | split("arn:aws:s3:::")[1]')

define docker
	@docker run -v $(PWD):/build/go/src/code.justin.tv/devhub/mdaas-discovery-tags-validator:delegated -u 61000:61000 -w /build/go/src/code.justin.tv/devhub/mdaas-discovery-tags-validator	--rm $(docker_build_image) /bin/bash -c "echo \"running $(1) in docker\" && $(1)"
endef

# Build
.PHONY: build
build:
	GOOS=linux go build -o build/main cmd/TwitchE2TaggingServiceLambda/main.go
	cd build && zip function.zip ./main
	cd build && cp function.zip function-$(date).zip
	
.PHONY: setup
setup:
	which go || (echo "install go" && exit 1)
	go get github.com/vektra/mockery/... 
	go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
	go get -u github.com/go-bindata/go-bindata/...

.PHONY: generate
generate:
	go generate ./...

.PHONY: test
test:
	go test ./...

.PHONY: bench
bench:
	go test -bench=. ./...  

.PHONY: fmt
fmt:
	go fmt ./...

.PHONY: lint
lint:
	golangci-lint run
	go run ./vendor/code.justin.tv/tshadwell/nice/cmd/nicer ./...

.PHONY: build-docker
build-docker:
	$(call docker, make build)

.PHONY: lint-docker
lint-docker: 
	$(call docker, make setup && make lint)

.PHONY: test-docker
test-docker:
	$(call docker, make test)

.PHONY: deploy-docker
deploy-docker:  build-docker
	aws lambda update-function-code --function-name $(LAMBDA_ARN) --zip-file fileb://$(PWD)/build/function.zip
	aws s3 cp ./build/function-$(date).zip s3://$(BUCKET_ARN)/
	aws s3 cp ./build/function.zip s3://$(BUCKET_ARN)/

.PHONY: config
config:
	go-bindata -o data/data.go -pkg=data data/data/

.PHONY: tags
tags:
	rm ./data/staging-tags.gen.go
	rm ./data/prod-tags.gen.go
	go run cmd/tag_to_uuid_generator.go/main.go
	make fmt

