SHELL := /bin/bash
PROJECT=mimir
GOPATH ?= $(shell go env GOPATH)

# Ensure GOPATH is set before running build process.
ifeq "$(GOPATH)" ""
  $(error Please set the environment variable GOPATH before running `make`)
endif

GOENV   	    := GO111MODULE=on CGO_ENABLED=0
GO                  := $(GOENV) go
GOBUILD             := $(GO) build $(BUILD_FLAG)
GOTEST              := $(GO) test -v --count=1 --parallel=1 -p=1
GORUN               := $(GO) run
TEST_LDFLAGS        := ""

PACKAGE_LIST        := go list ./...| grep -vE "cmd"
PACKAGES            := $$($(PACKAGE_LIST))

# Targets
.PHONY: server_dev build_linux test

CURDIR := $(shell pwd)
PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))
export PATH := $(CURDIR)/bin/:$(PATH)

# run starts the server with dev config
server_dev:
	$(GORUN) $(CURIR)cmd/server/main.go -c=$(CURIR)config_dev.yaml

build_auth_linux: lint
	GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -o bin/auth cmd/oauth2/main.go

build_linux: lint
	GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -o bin/mimird cmd/server/main.go

build_pgdy_collector_linux: lint
	cd biz/pagerduty_alert/ && GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -o $(PROJECT_DIR)/bin/pgdy-collector .

package_pgdy_collector:
	cd bin && zip pgdy-collector.zip pgdy-collector

package_gcp_collector:
	$(call package_gcp_collector)

docker_push:
	docker push ${IMG}

docker_build_server:
	docker build -t ${IMG} .

docker_build_flink:
	cd engine/flink/ && docker build -t ${IMG} .

docker_build_dbaas_snapshot:
	cd biz/dbaas_snapshoter/ && docker build -t ${IMG} .

docker_build_table_checker:
	cd jobs/table_checker/ && docker build -t ${IMG} .

docker_build_default_mapper:
	cd biz/mapper/ && docker build -t ${IMG} .

cli: lint
	$(GOBUILD) -o bin/mim ./cmd/cli

test:
	$(GOTEST) ./...

## Run golangci-lint linter
lint: golangci-lint
	$(GOLANGCI_LINT) --timeout 7m0s run ./...

## Run golangci-lint linter and perform fixes
lint-fix: golangci-lint
	$(GOLANGCI_LINT) run --fix ./...

GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
golangci-lint: ## Download golangci-lint locally if necessary
	$(call go-get-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.41.1)

# go-get-tool will 'go get' any package $2 and install it to $1.
define go-get-tool
@[ -f $(1) ] || { \
set -e ;\
TMP_DIR=$$(mktemp -d) ;\
cd $$TMP_DIR ;\
go mod init tmp ;\
echo "Downloading $(2)" ;\
GOBIN=$(PROJECT_DIR)/bin go get $(2) ;\
rm -rf $$TMP_DIR ;\
}
endef

define package_gcp_collector
	python -m venv $(PROJECT_DIR)/bin/gcp-cost
	source $(PROJECT_DIR)/bin/gcp-cost/bin/activate && pip install google-cloud-bigquery && pip install google-auth
	cd $(PROJECT_DIR)/bin/gcp-cost/lib/python3.7/site-packages && zip -r9 $(PROJECT_DIR)/bin/gcp_cost.zip .
	cd $(PROJECT_DIR)/biz/dbaas_gcp_cost && zip -g $(PROJECT_DIR)/bin/gcp_cost.zip gcp_cost_ananlysis_billing_resources.py product_mapping.csv
	rm -rf $(PROJECT_DIR)/bin/gcp-cost
endef
