# Meson build system wrapper
# Run `meson configure build` to see/change build options
#
# Examples:
#   make                 # Build (sets up meson if needed)
#   sudo make install    # Install to /usr/local
#   make clean           # Remove build directory
#   make reconfigure     # Wipe and reconfigure build

-include .local.mk

.PHONY: all install uninstall clean setup setup-test reconfigure test test-unit test-render test-lua-compat test-check test-signal test-nested-pointer test-ipc-socket test-integration test-orchestrator test-cache-equivalence test-restart test-one-restart test-asan test-one test-visual test-one-visual test-ci test-fast build-test build-bench bench-run bench-run-live bench-json bench-baseline bench-compare bench-check bench-memory bench-flamegraph bench-diff bench-heaptrack profile profile-lua profile-save profile-diff

# Default build: optimized release, no sanitizers
all:
	@test -d build || meson setup build -Dbuildtype=release -Db_sanitize=none $(if $(LUA_PKG),-Dlua_pkg=$(LUA_PKG),) $(MESON_OPTS)
	ninja -C build

# AddressSanitizer + UBSan build (separate dir, for development)
asan:
	@test -d build-asan || meson setup build-asan -Db_sanitize=address,undefined -Dtest_pam=true $(if $(LUA_PKG),-Dlua_pkg=$(LUA_PKG),) $(MESON_OPTS)
	meson configure build-asan -Dtest_pam=true
	ninja -C build-asan

# Configure the test build dir without building anything in it
setup-test:
	@test -d build-test || meson setup build-test -Db_sanitize=none -Dtest_pam=true $(if $(LUA_PKG),-Dlua_pkg=$(LUA_PKG),) $(MESON_OPTS)

# Build for tests: NO ASAN (fast) - explicitly disable sanitizers, enable test PAM stub
build-test: setup-test
	ninja -C build-test

# meson install never deletes, and a stale 2.0 module would shadow the error a config should get.
install:
	dir=$$(meson introspect build --buildoptions | python3 -c 'import json, os, sys; o = {x["name"]: x["value"] for x in json.load(sys.stdin)}; print(os.path.join(o["prefix"], o["datadir"], "somewm", "lua"))') && rm -rf "$(DESTDIR)$$dir"
	meson install -C build --skip-subprojects

uninstall:
	ninja -C build uninstall

clean:
	rm -rf build build-test build-asan

# Just setup (useful for IDE integration)
setup:
	meson setup build

# Wipe and reconfigure
reconfigure:
	rm -rf build
	meson setup build

# =============================================================================
# Testing
# =============================================================================

# Run all tests (fast, no ASAN)
test: test-unit test-check test-signal test-nested-pointer test-ipc-socket test-orchestrator test-cache-equivalence test-restart test-integration

# Parse lua/ with every installed Lua version (no compositor needed)
test-lua-compat:
	@./tests/check-lua-compat.sh

# Unit tests only (busted and the C renderer test; no compositor needed)
test-unit: test-lua-compat test-render
	@./tests/run-unit.sh

# C unit tests: hand-built commands and production-solver declarations.
# Build the test binaries without rebuilding the whole compositor.
test-render: setup-test
	@ninja -C build-test somewm test-render test-clay-solver test-clay-aspect
	@meson test -C build-test --suite unit --print-errorlogs --no-rebuild

# Check mode tests (no compositor needed, tests somewm --check)
test-check: build-test
	@./tests/test-check-mode.sh ./build-test/somewm

# SIGTERM regression test: a headless somewm must exit on SIGTERM
test-signal: build-test
	@./tests/test-signal-term.sh ./build-test/somewm

# An exiting somewm leaves a newer instance's IPC socket alone
test-ipc-socket: build-test
	@./tests/test-ipc-socket-handoff.sh ./build-test/somewm ./build-test/somewm-client
	@./tests/test-ipc-socket-live-owner.sh ./build-test/somewm ./build-test/somewm-client

# Nested-backend pointer mapping: two compositors, one hosting the other
test-nested-pointer: build-test
	@./tests/test-nested-pointer-mapping.sh ./build-test/somewm ./build-test/somewm-client

# Test orchestrator (somewm-client test ...): spawns headless nested compositor
test-orchestrator: build-test
	@./tests/test-test-orchestrator.sh ./build-test/somewm ./build-test/somewm-client

# The bundled config dumps the same tree with the fragment cache off
test-cache-equivalence: build-test
	@./tests/test-clay-cache-equivalence.sh ./build-test/somewm ./build-test/somewm-client

# Restart tests: assertions on both sides of a real awesome.restart()
test-restart: build-test
	@SOMEWM=./build-test/somewm SOMEWM_CLIENT=./build-test/somewm-client ./tests/run-restart.sh

# Run single restart test, keeping its instance log
# Usage: make test-one-restart TEST=tests/restart/notify-after-restart.sh
test-one-restart: build-test
ifndef TEST
	@echo "Usage: make test-one-restart TEST=tests/restart/restart-executes.sh"
	@exit 1
endif
	@KEEP_LOGS=1 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-restart.sh $(TEST)

# Integration tests (visual mode by default, no ASAN)
test-integration: build-test
	@SOMEWM=./build-test/somewm SOMEWM_CLIENT=./build-test/somewm-client ./tests/run-integration.sh

# Integration tests with ASAN (slower, catches memory bugs). The C unit tests
# run here too, since the ASAN build is where they are worth the most.
test-asan: asan
	@meson test -C build-asan --suite unit --print-errorlogs
	@SOMEWM=./build-asan/somewm SOMEWM_CLIENT=./build-asan/somewm-client ./tests/run-integration.sh

# The integration tests CI runs, headless, here and in CI's integration step.
# Tests that need external apps or spawn clients are left out.
test-ci: build-test
	@spawning=$$(grep -rl 'require.*_client' tests/test-*.lua | xargs -I{} basename {}); \
	 tests=$$(find tests -name 'test-*.lua' -type f \
	   ! -name 'test-xwayland-*' \
	   ! -name 'test-layer-shell-*' \
	   ! -name 'test-dbus-error.lua' \
	   ! -name 'test-transient-stacking.lua' \
	   ! -name 'test-output-fake-screen.lua' \
	   $$(printf '! -name %s ' $$spawning) \
	   | sort); \
	 HEADLESS=1 LIBSEAT_BACKEND=noop TEST_TIMEOUT=45 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-integration.sh $$tests

# Fast test suite using persistent compositor (10x faster)
test-fast: build-test
	@PERSISTENT=1 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-integration.sh

# Run single test (TDD workflow, no ASAN for speed)
# Usage: make test-one TEST=tests/test-focus.lua
test-one: build-test
ifndef TEST
	@echo "Usage: make test-one TEST=tests/test-my-feature.lua"
	@exit 1
endif
ifeq ($(TEST),tests/test-nested-pointer-mapping.sh)
	@./tests/test-nested-pointer-mapping.sh ./build-test/somewm ./build-test/somewm-client
else
	@VERBOSE=1 \
	 TEST_TIMEOUT=10 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-integration.sh $(TEST)
endif

# Visual test mode - watch tests run in a window (like AwesomeWM's Xephyr)
test-visual: build-test
	@HEADLESS=0 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-integration.sh

# Visual single test - for debugging
test-one-visual: build-test
ifndef TEST
	@echo "Usage: make test-one-visual TEST=tests/test-my-feature.lua"
	@exit 1
endif
	@HEADLESS=0 \
	 VERBOSE=1 \
	 TEST_TIMEOUT=60 \
	 SOMEWM=./build-test/somewm \
	 SOMEWM_CLIENT=./build-test/somewm-client \
	 ./tests/run-integration.sh $(TEST)

# =============================================================================
# Benchmarking
# =============================================================================

# Build with bench instrumentation (no ASAN, debugoptimized)
build-bench:
	@test -d build-bench || meson setup build-bench -Db_sanitize=none -Dbuildtype=debugoptimized -Dbench=true
	ninja -C build-bench

# Run benchmarks in headless mode
bench-run: build-bench
	@HEADLESS=1 \
	 SOMEWM=./build-bench/somewm \
	 SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/run-all.sh

# Run benchmarks against the live compositor session
bench-run-live:
	@HEADLESS=0 \
	 SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/run-all.sh

# Record perf profile during benchmarks (30s default, override with PERF_DURATION=N)
bench-flamegraph: build-bench
	perf record -g --call-graph dwarf -p $$(pidof somewm) -o perf-bench.data -- sleep $${PERF_DURATION:-30}
	perf script -i perf-bench.data | stackcollapse-perf.pl | flamegraph.pl > somewm-bench-flamegraph.svg
	@echo "Flamegraph: somewm-bench-flamegraph.svg"

# Generate differential flamegraph between two perf recordings
# Usage: make bench-diff SYNC=perf-sync.data QUEUE=perf-queue.data
bench-diff:
ifndef SYNC
	@echo "Usage: make bench-diff SYNC=perf-sync.data QUEUE=perf-queue.data"
	@exit 1
endif
ifndef QUEUE
	@echo "Usage: make bench-diff SYNC=perf-sync.data QUEUE=perf-queue.data"
	@exit 1
endif
	perf script -i $(SYNC) | stackcollapse-perf.pl > /tmp/sync.folded
	perf script -i $(QUEUE) | stackcollapse-perf.pl > /tmp/queue.folded
	difffolded.pl /tmp/sync.folded /tmp/queue.folded | flamegraph.pl > somewm-bench-diff.svg
	@echo "Differential flamegraph: somewm-bench-diff.svg"

# Run benchmarks with JSON output capture (against live session)
bench-json: build-bench
	@JSON=1 \
	 SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/run-all.sh

# Save current results as baseline for this branch
bench-baseline: bench-json
	./tests/bench/bench-save-baseline.sh

# Compare two result sets: make bench-compare A=results/dir-a B=results/dir-b
bench-compare:
	@lua5.1 tests/bench/bench-stats.lua $(A) $(B) 2>/dev/null \
	 || luajit tests/bench/bench-stats.lua $(A) $(B) 2>/dev/null \
	 || lua tests/bench/bench-stats.lua $(A) $(B)

# Check for regressions against baseline
bench-check: bench-json
	@lua5.1 tests/bench/bench-stats.lua \
	 tests/bench/results/baselines/$$(git branch --show-current) \
	 $$(ls -td tests/bench/results/20* | head -1) 2>/dev/null \
	 || luajit tests/bench/bench-stats.lua \
	 tests/bench/results/baselines/$$(git branch --show-current) \
	 $$(ls -td tests/bench/results/20* | head -1) 2>/dev/null \
	 || lua tests/bench/bench-stats.lua \
	 tests/bench/results/baselines/$$(git branch --show-current) \
	 $$(ls -td tests/bench/results/20* | head -1)

# Run memory trend analysis (uses its own headless compositor)
bench-memory: build-bench
	@SOMEWM=./build-bench/somewm \
	 SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/bench-memory-runner.sh

# --- Profiling (live session) ---

# Profile the running compositor for DURATION seconds (default: 30)
# Usage: make profile
#        make profile DURATION=60
profile:
	@SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/profile-session.sh $(DURATION)

# Profile with Lua function breakdown via jit.p
# Usage: make profile-lua
#        make profile-lua DURATION=60
profile-lua:
	@SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/profile-session.sh --lua $(DURATION)

# Save a profile as a named baseline for later comparison
# Usage: make profile-save LABEL=before-refactor
profile-save:
ifndef LABEL
	@echo "Usage: make profile-save LABEL=<name>" >&2
	@exit 1
endif
	@SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/profile-session.sh --save $(LABEL) $(DURATION)

# Compare current profile against a saved baseline
# Usage: make profile-diff LABEL=before-refactor
profile-diff:
ifndef LABEL
	@echo "Usage: make profile-diff LABEL=<name>" >&2
	@exit 1
endif
	@SOMEWM_CLIENT=./build-bench/somewm-client \
	 ./tests/bench/profile-session.sh --diff $(LABEL) $(DURATION)

# Memory profiling with heaptrack
bench-heaptrack: build-bench
	heaptrack ./build-bench/somewm
