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)

# Deployment target (front server) and ET server behind the tunnel.
HOST :=
UPSTREAM :=
# Extra etrelay flags, e.g. make deploy ARGS=--debug
ARGS ?=

.PHONY: show lint format check build static release deploy logs 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

deploy: static
	scp $(STATIC_BIN) $(HOST):/tmp/$(NAME)
	sed -e 's#@UPSTREAM@#$(UPSTREAM)#' -e 's#@ARGS@#$(ARGS)#' $(NAME).service | ssh $(HOST) 'cat > /etc/systemd/system/$(NAME).service'
	ssh $(HOST) 'install -m 755 /tmp/$(NAME) /usr/local/bin/$(NAME) && rm /tmp/$(NAME) \
		&& systemctl daemon-reload && systemctl enable $(NAME) && systemctl restart $(NAME) \
		&& systemctl --no-pager status $(NAME)'

logs:
	ssh $(HOST) 'journalctl -u $(NAME) -n 50 --no-pager'

# 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
