ROOT_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))

NAME := etrelay
VERSION := $(shell grep -m1 '^version' Cargo.toml | cut -d '"' -f2)
GNU := x86_64-unknown-linux-gnu
MUSL := x86_64-unknown-linux-musl

# Release artifacts: <name>-v<version>-<target triple> (+ .sha256).
DIST_DIR := $(ROOT_DIR)dist
DYNAMIC_BIN := $(DIST_DIR)/$(NAME)-v$(VERSION)-$(GNU)
STATIC_BIN := $(DIST_DIR)/$(NAME)-v$(VERSION)-$(MUSL)

.PHONY: show lint format check build static release diagrams clean

show:
	@echo "$(NAME) version: $(VERSION)"

lint:
	cargo clippy --fix --allow-dirty

format:
	cargo fmt --all

check: lint format

# Dynamic (glibc): runs on hosts with the same or newer glibc.
build: check
	cargo build --release --target $(GNU)
	@$(call dist,$(GNU),$(DYNAMIC_BIN))

# Static (musl): runs on any x86_64 Linux. Pure Rust, no musl-gcc needed.
static: check
	rustup target add $(MUSL)
	cargo build --release --target $(MUSL)
	@$(call dist,$(MUSL),$(STATIC_BIN))

release: build static

# PlantUML sources (diagrams/*.puml) -> PNG next to them, used by ENGINE.md.
diagrams:
	plantuml -tpng $(ROOT_DIR)diagrams/*.puml
	@ls -1 $(ROOT_DIR)diagrams/*.png

clean:
	cargo clean
	rm -rf $(DIST_DIR)

# $(call dist,<target triple>,<artifact path>): copy the release binary to dist/ + checksum.
define dist
mkdir -p $(DIST_DIR)
cp $(ROOT_DIR)target/$(1)/release/$(NAME) $(2)
cd $(DIST_DIR) && sha256sum $(notdir $(2)) > $(notdir $(2)).sha256
ls -lh $(2)
endef

# Deployment targets (deploy, logs, status...) kept with the infra config, reached through
# the local .deploy symlink (gitignored). Optional: silently skipped when absent.
ETRELAY_DIR := $(patsubst %/,%,$(ROOT_DIR))
-include $(ROOT_DIR).deploy/Makefile
