SHELL := /usr/bin/env bash
.DEFAULT_GOAL := help

GO ?= go
GO_TOOL := $(GO) tool
DOCKER ?= docker
API_DIR := $(abspath ../api)
API_PREPARED ?= 0
# The runner and its sandbox are Linux-only, so lint analyzes Linux code. The
# linter binary is built for the host first; GOOS then selects only the
# analyzed packages.
LINT_GOOS ?= linux
GOLANGCI_LINT := bin/golangci-lint
RUNNER_IMAGE ?= lincodex-runner-dev:local
SANDBOX_TEST_IMAGE ?= lincodex-runner-sandbox-test:local
# Recorded in the A16 report; reading Git state changes nothing.
RUNNER_VERSION ?= $(shell git describe --always --dirty --abbrev=12 2>/dev/null || echo unknown)
# A16 report directory; .gitignore keeps reports out of Git.
A16_REPORT_DIR ?= $(CURDIR)/.reports
# Extra RUNNER_* settings for the A16 suite, for example
# A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096" to see a weakened limit fail.
A16_ENV ?=
# Architecture of the A16 bundle for a runner host.
A16_GOARCH ?= amd64
A16_BUNDLE_DIR := bin/a16-bundle
# DEVELOPMENT ONLY: --privileged gives nsjail namespaces and a writable
# cgroup v2 tree inside the Docker Desktop VM; exec on the work tmpfs lets
# built Go solutions run. Production never uses these flags.
SANDBOX_RUN := $(DOCKER) run --rm --privileged --cgroupns=private --network=none \
	--tmpfs /var/lib/lincodex-runner/work:size=128m,mode=0711,exec
OGEN_ARGS := -config codegen/ogen.yml --package api --clean ../api/runner/openapi.bundle.yml

##@ Build

.PHONY: build
build: ## Build the runner binary for Linux
	@mkdir -p bin
	CGO_ENABLED=0 GOOS=linux $(GO) build -buildvcs=false -trimpath -o bin/lincodex-runner ./cmd/runner

.PHONY: deps install
deps: ## Download pinned Go module dependencies
	$(GO) mod download

install: deps ## Install module-pinned Go tools without global changes
	@$(GO) version
	@$(GO_TOOL) ogen --version
	@$(GO_TOOL) golangci-lint version

.PHONY: tidy
tidy: ## Tidy application and tool dependencies
	$(GO) mod tidy

.PHONY: clean
clean: ## Remove local build and test artifacts
	rm -rf bin coverage.out

##@ Code generation

.PHONY: generate gen
generate gen: ## Generate the ogen server from the code runner contract
	@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
	$(GO_TOOL) ogen --target internal/api $(OGEN_ARGS)

.PHONY: check-generated
check-generated: ## Check the generated server against the bundled contract without rewriting it
	@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-check.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
	$(GO_TOOL) ogen --target "$$temporary_dir" $(OGEN_ARGS) >/dev/null 2>&1; \
	diff -r internal/api "$$temporary_dir"

##@ Format, lint, and test

.PHONY: $(GOLANGCI_LINT)
$(GOLANGCI_LINT):
	@mkdir -p bin
	$(GO) build -o $(GOLANGCI_LINT) github.com/golangci/golangci-lint/v2/cmd/golangci-lint

.PHONY: fmt
fmt: $(GOLANGCI_LINT) ## Format Go sources
	GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt ./...

.PHONY: fmt-check
fmt-check: $(GOLANGCI_LINT) ## Check Go formatting without modifying files
	@unformatted=$$(gofmt -l $$(find . -name '*.go' -type f -not -path './bin/*')); \
	if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi
	@formatter_diff=$$(GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt --diff ./...); \
	if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi

.PHONY: lint
lint: $(GOLANGCI_LINT) ## Run golangci-lint for Linux, including the isolation tests
	GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) run ./...

.PHONY: test
test: ## Run unit tests with the race detector; they need no sandbox
	$(GO) test -race -count=1 ./...

.PHONY: image
image: ## Build the runner image for local development
	$(DOCKER) build --file Dockerfile --tag "$(RUNNER_IMAGE)" .

.PHONY: sandbox-test-image
sandbox-test-image: image
	$(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --build-arg RUNNER_VERSION="$(RUNNER_VERSION)" --tag "$(SANDBOX_TEST_IMAGE)" .

.PHONY: test-sandbox
test-sandbox: sandbox-test-image ## Run reference solutions and the A16 suite in a privileged dev container
	$(SANDBOX_RUN) "$(SANDBOX_TEST_IMAGE)"

.PHONY: test-a16
test-a16: sandbox-test-image ## Run only the A16 hostile-program suite locally and write a report to .reports/
	@mkdir -p "$(A16_REPORT_DIR)"
	$(SANDBOX_RUN) $(foreach setting,$(A16_ENV),--env $(setting)) \
		--volume "$(A16_REPORT_DIR):/reports" \
		--env RUNNER_A16_REPORT=/reports/a16-$$(date -u +%Y%m%dT%H%M%SZ).json \
		"$(SANDBOX_TEST_IMAGE)" -test.run '^TestA16'

.PHONY: a16-bundle
a16-bundle: ## Build the A16 suite for a runner host (A16_GOARCH, default amd64) into bin/a16-bundle.tar.gz
	rm -rf "$(A16_BUNDLE_DIR)"
	mkdir -p "$(A16_BUNDLE_DIR)/testdata"
	CGO_ENABLED=0 GOOS=linux GOARCH=$(A16_GOARCH) $(GO) test -c -tags sandbox \
		-ldflags "-X lincodex/runner/internal/isolationtest.runnerVersion=$(RUNNER_VERSION)" \
		-o "$(A16_BUNDLE_DIR)/isolation.test" ./internal/isolationtest
	cp -R testdata/hostile "$(A16_BUNDLE_DIR)/testdata/hostile"
	cp scripts/run-a16.sh "$(A16_BUNDLE_DIR)/run-a16.sh"
	tar -C bin -czf bin/a16-bundle.tar.gz a16-bundle

.PHONY: check
check: ## Run formatting, build, unit, generated drift, and lint checks
	$(MAKE) --no-print-directory fmt-check
	$(MAKE) --no-print-directory build
	$(MAKE) --no-print-directory test
	$(MAKE) --no-print-directory check-generated
	$(MAKE) --no-print-directory lint

##@ Help

.PHONY: help
help: ## Show available targets
	@awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n  make -C runner <target>\n"} /^[a-zA-Z0-9_-]+:.*##/ {printf "  %-16s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST)
