SHELL := /usr/bin/env bash
.SHELLFLAGS := -eu -o pipefail -c
.DEFAULT_GOAL := help

ROOT := $(abspath ..)
BIN := $(CURDIR)/.bin
REPORTS := $(CURDIR)/reports
CACHE := $(CURDIR)/.cache
TRIVY ?= $(BIN)/trivy
GITLEAKS ?= $(BIN)/gitleaks
GITLEAKS_CONFIG ?= $(CURDIR)/gitleaks/gitleaks.toml
SEMGREP ?= $(BIN)/semgrep
GOVULNCHECK ?= $(BIN)/govulncheck
UV ?= uv
GO ?= go
DOCKER ?= docker
PYTHON ?= python3
export SEMGREP_SEND_METRICS := off
export SEMGREP_ENABLE_VERSION_CHECK := 0

.PHONY: help install install-trivy install-gitleaks install-semgrep install-go check filesystem secrets go semgrep test rule-test images

help: ## Show security commands.
	@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST)

install: ## Install current stable scanners locally without changing global tools.
	$(MAKE) install-trivy install-gitleaks install-semgrep install-go

install-trivy: ## Install the latest stable Trivy release with SHA256 verification.
	$(PYTHON) install.py trivy

install-gitleaks: ## Install the latest stable Gitleaks release with SHA256 verification.
	$(PYTHON) install.py gitleaks

install-semgrep: ## Install Semgrep in an isolated uv tool environment.
	UV_TOOL_DIR="$(CURDIR)/.tools" UV_TOOL_BIN_DIR="$(BIN)" UV_PYTHON_INSTALL_DIR="$(CURDIR)/.tools/python" UV_CACHE_DIR="$(CACHE)/uv" $(UV) tool install --python 3.13 --upgrade semgrep

install-go: ## Install the current govulncheck without modifying the backend module.
	GOBIN="$(BIN)" $(GO) install golang.org/x/vuln/cmd/govulncheck@latest

$(REPORTS) $(CACHE):
	mkdir -p "$@"

check: ## Run every source check and fail if any scanner fails or reports blocking findings.
	@status=0; for target in filesystem secrets go semgrep; do \
		$(MAKE) "$$target" || status=1; \
	done; exit "$$status"

filesystem: | $(REPORTS) $(CACHE) ## Scan dependency manifests and infrastructure configuration.
	@rm -f "$(REPORTS)/trivy-filesystem.json" "$(REPORTS)/trivy-version.txt"
	@cd "$(ROOT)"; status=0; \
	$(TRIVY) fs --config security/trivy/filesystem.yml --cache-dir "$(CACHE)/trivy" --output "$(REPORTS)/trivy-filesystem.json" . || status=$$?; \
	if [ -f "$(REPORTS)/trivy-filesystem.json" ]; then \
		$(TRIVY) convert --format table --scanners vuln,misconfig "$(REPORTS)/trivy-filesystem.json" || { if [ "$$status" -eq 0 ]; then status=1; fi; }; \
	else \
		echo 'Trivy did not create the filesystem report.' >&2; \
		if [ "$$status" -eq 0 ]; then status=1; fi; \
	fi; \
	$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt" || status=1; \
	exit "$$status"

secrets: | $(REPORTS) ## Scan current files and full Git history with redacted output.
	@rm -f "$(REPORTS)/gitleaks-files.json" "$(REPORTS)/gitleaks-history.json" "$(REPORTS)/gitleaks-version.txt"
	$(PYTHON) "$(CURDIR)/scan_inputs.py" --root "$(ROOT)" --scanner "$(GITLEAKS)" --config "$(GITLEAKS_CONFIG)" --reports "$(REPORTS)"

go: | $(REPORTS) ## Scan reachable vulnerable Go symbols; preserve the native failing exit status.
	@rm -f "$(REPORTS)/govulncheck.txt" "$(REPORTS)/govulncheck-version.txt"
	$(GOVULNCHECK) -version > "$(REPORTS)/govulncheck-version.txt"
	cd "$(ROOT)/backend" && $(GOVULNCHECK) ./... 2>&1 | tee "$(REPORTS)/govulncheck.txt"

semgrep: | $(REPORTS) ## Check frontend and ML source with reviewed local rules.
	@rm -f "$(REPORTS)/semgrep.json" "$(REPORTS)/semgrep-version.txt"
	$(SEMGREP) --version > "$(REPORTS)/semgrep-version.txt"
	cd "$(ROOT)" && $(SEMGREP) scan --strict --error --disable-nosem --metrics off --config security/semgrep/frontend.yml --config security/semgrep/python.yml --json-output "$(REPORTS)/semgrep.json" frontend/src ml/src

rule-test: ## Validate security rules against positive and negative fixtures.
	cd "$(ROOT)" && $(SEMGREP) --test --metrics off --config security/semgrep security/semgrep/tests

test: rule-test ## Check rule fixtures, installer integrity, and scanner failure handling.
	PYTHONDONTWRITEBYTECODE=1 $(PYTHON) -m unittest discover -s tests

images: | $(REPORTS) $(CACHE) ## Build and scan the exact backend, frontend, and ML images without publishing.
	@for service in backend frontend ml; do rm -f "$(REPORTS)/trivy-$$service.json" "$(REPORTS)/$$service-image-id.txt"; done
	@rm -f "$(REPORTS)/trivy-version.txt"
	$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt"
	@status=0; for service in backend frontend ml; do \
		tag="lincodex-security-$$service:local"; \
		context="$(ROOT)"; if [ "$$service" = backend ]; then context="$(ROOT)/backend"; fi; \
		if $(DOCKER) build --pull -f "$(ROOT)/$$service/Dockerfile" -t "$$tag" "$$context"; then \
			if image_id=$$($(DOCKER) image inspect --format '{{.Id}}' "$$tag"); then \
				printf '%s\n' "$$image_id" > "$(REPORTS)/$$service-image-id.txt"; \
				report="$(REPORTS)/trivy-$$service.json"; \
				$(TRIVY) image --image-src docker --config trivy/image.yml --cache-dir "$(CACHE)/trivy" --output "$$report" "$$image_id" || status=1; \
				if [ -f "$$report" ]; then \
					$(TRIVY) convert --format table --scanners vuln,misconfig "$$report" || status=1; \
				else \
					printf 'Trivy did not create the %s image report.\n' "$$service" >&2; status=1; \
				fi; \
			else status=1; fi; \
		else status=1; fi; \
	done; \
	$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt" || status=1; \
	exit "$$status"
