# Binaries
TF_BIN = _tools/bin/terraform

clean:
	rm -rf ./terraform/.terraform
	rm -rf ./builds
.PHONY: clean

bench:
	docker-compose up -d
	go test -v -bench=BenchmarkTenureDB ./internal/redis
.PHONY: bench

# Generate Twirp files based on the ./destinytwirp/*.proto files.
twirp: destinytwirp/*.proto
	retool do protoc --proto_path=$(GOPATH)/src:. --twirp_out=$(CURDIR) --go_out=$(CURDIR) ./destinytwirp/*.proto

# Run locally.
run:
	AWS_PROFILE=twitch-subs-dev go run cmd/destiny/main.go destiny
.PHONY: run

# Run all the tests in a Docker container. This is used by the Jenkins job.
docker-test:
	# Bootstrap dependent Docker containers needed to run tests.
	docker-compose -f jenkins/docker-compose.yml run --rm tests
.PHONY: docker-test

# Sync dependencies
dep: Gopkg.lock Gopkg.toml
	@echo 'Fetching dependencies...'
	dep ensure

install: _dep _retool
	$(CURDIR)/_tools/bin/retool sync

_retool:
	GOPATH=$(CURDIR)/_tools go install github.com/twitchtv/retool/...
.PHONY: _retool

### Terraform
TF_STATE_ROOT = ./state

# Automatically format Terraform files.
terraform-fmt:
	@$(TF_BIN) fmt
.PHONY: terraform-fmt

# Plan Terraform against a specific environment.
# 	Usage:
#
#      `make plan env=staging`
#      `make plan env=production`
#
# The plan will be saved to terraform/state/$env.plan and `make apply ...` will use
# the recent plan.
plan: terraform-fmt
	@mkdir -p terraform/$(TF_STATE_ROOT)
	@test "${env}" || (echo '$$env required' && exit 1)
	@cd ./terraform && ../$(TF_BIN) init
	@cd ./terraform && ../$(TF_BIN) plan \
		-state=$(TF_STATE_ROOT)/$(env).tfstate \
		-var-file=$(env).tfvars \
		-out $(TF_STATE_ROOT)/$(env).plan
.PHONY: plan

# Apply a previous plan that was created via the `make plan env=$env` command.
# 	Usage:
#
#      `make apply env=staging`
#      `make apply env=production`
apply:
	@test "${env}" || (echo '$$env required' && exit 1)
	@cd ./terraform && ../$(TF_BIN) apply -refresh -state-out=$(TF_STATE_ROOT)/$(env).tfstate  $(TF_STATE_ROOT)/$(env).plan
.PHONY: apply

ecr-aws:
	@$(shell AWS_PROFILE=twitch-subs-aws aws ecr get-login --no-include-email --region us-west-2)
.PHONY: ecr-aws

build-linux:
	@mkdir -p builds
	@GOOS=linux go build -o builds/destiny-linux cmd/destiny/main.go
.PHONY: build-linux