.PHONY: all framework

default: all

GOOS    := $(if $(GOOS),$(GOOS),$(shell go env GOOS))
GOARCH  := $(if $(GOARCH),$(GOARCH),$(shell go env GOARCH))
GOENV   := CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH)
GO      := $(GOENV) go
GOBUILD := $(GO) build $(BUILD_FLAGS)
GOTEST  := CGO_ENABLED=0 $(GO) test -p 4
LDFLAGS += -s -w
CHECK_LDFLAGS += $(LDFLAGS)

FUNCTIONS := runtime scheduler
GO_JOBS := unstable-plan

PYTHON_JOB_PATH := $(shell pwd)/jobs
PYTHON := python3.9
PIP := $(PYTHON) -m pip

############### golang commands ###############

.PHONY: all
all: mod lint_fix test build

.PHONY: test
test:
	go test -race -covermode=atomic -coverprofile=coverage.out -coverpkg=./... ./...
	go tool cover -html=coverage.out -o coverage.html

.PHONY: build
build: build-framework build-go-jobs

.PHONY: build-framework
build-framework:
	${MAKE} ${MAKEOPTS} $(foreach function, ${FUNCTIONS}, build-framework-${function})

.PHONY: build-go-jobs
build-go-jobs:
	${MAKE} ${MAKEOPTS} $(foreach job, ${GO_JOBS}, build-go-job-${job})

.PHONY: build-framework-%
build-framework-%:
	cd framework/$* && $(GOBUILD) -o handler

.PHONY: build-go-job-%
build-go-job-%:
	cd jobs/global/$* && $(GOBUILD) -o handler

.PHONY: clean
clean:
	${MAKE} ${MAKEOPTS} $(foreach function, ${FUNCTIONS}, clean-framework-${function})
	${MAKE} ${MAKEOPTS} $(foreach job, ${GO_JOBS}, clean-job-${job})
	rm -f '"$(shell go env GOCACHE)/../golangci-lint"'
	go clean -i -cache -testcache -fuzzcache -x

.PHONY: clean-framework-%
clean-framework-%:
	@rm -f framework/$*/handler

.PHONY: clean-job-%
clean-job-%:
	@rm -f jobs/global/$*/handler

.PHONY: mod
mod:
	tools/go_mod_tidy_recursively.sh

.PHONY: install-tools
install-tools:
	cd tools && go install $(shell cd tools && go list -f '{{ join .Imports " " }}' -tags=tools)

.PHONY: lint
lint:
	golangci-lint run --timeout 10m0s

.PHONY: lint_fix
lint_fix:
	golangci-lint run --fix --timeout 10m0s

############### python commands ###############

.PHONY: py-venv
py-venv:
	test -d "venv" || ${PYTHON} -m venv venv
	. venv/bin/activate

.PHONY: py-install-job-dependencies
py-install-job-dependencies: py-venv
	find ${PYTHON_JOB_PATH} -name "requirement*" -type f -exec ${PIP} install -r '{}' ';'

.PHONY: py-install-dev-dependencies
py-install-dev-dependencies: py-venv
	${PIP} install -r requirements-dev.txt

.PHONY: py-fmt
py-fmt: py-venv
	isort -l 100 --skip-glob *.ipynb jobs/
	black -l 100 --exclude .+\.ipynb jobs/

.PHONY: py-lint
py-lint: py-venv
	#flake8 --max-line-length 100 jobs/
	black -l 100 --exclude .+\.ipynb --check jobs/
	#mypy --ignore-missing-imports jobs/
