#!/usr/bin/env bash
# Run `rustdoc --test` over every Markdown file under `docs/` so the
# `no_run` snippets in the widget catalogue and cookbook get the same
# typecheck guard `cargo test --doc` provides for in-source doctests.
# Files with no Rust code blocks are a no-op for rustdoc.
#
# `no_run` blocks compile but do not execute — that is what we want here
# because none of the snippets has a meaningful side effect outside a
# real Wayland session and the goal is to catch API drift, not to
# integration-test the runtime.
#
# Output mirrors `cargo test`'s shape: one PASS / FAIL line per file
# with rustdoc's compile output streamed through. The script exits
# non-zero on the first file that fails so CI fails the job cleanly.

set -euo pipefail

REPO_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
cd "$REPO_ROOT"

# Build the library so an rlib lives under target/debug/ for --extern.
# `--lib` skips the examples / tests; the rlib is the only artefact we
# need.
cargo build --lib --quiet

# Cargo names the rlib `libltk-<hash>.rlib` under `target/debug/deps/`.
# The hash is unstable across rebuilds (it embeds the dependency graph),
# so we discover it instead of hard-coding it. `ls -t` orders by mtime
# so a stale rlib from a previous build cannot win.
RLIB="$( ls -t target/debug/deps/libltk-*.rlib 2>/dev/null | head -1 )"
if [ -z "$RLIB" ]; then
	echo "doctest-md: no libltk-*.rlib found in target/debug/deps/" >&2
	echo "doctest-md: did the cargo build above succeed?"      >&2
	exit 1
fi

# Pick the edition from Cargo.toml so we stay in lockstep with the
# package and a future bump from 2021 → 2024 just works.
EDITION="$( grep -E '^edition[[:space:]]*=' Cargo.toml | head -1 | awk -F\" '{ print $2 }' )"
if [ -z "$EDITION" ]; then
	EDITION="2021"
fi

failures=0
for f in docs/*.md; do
	# Each file gets its own synthetic crate name so rustdoc's diagnostics
	# are easy to attribute. `tr -c '[:alnum:]_' '_'` rewrites any
	# character a Rust crate name cannot contain (`-`, `.`, etc.).
	crate_name="$( basename "$f" .md | tr -c '[:alnum:]_' '_' )_md"

	echo "doctest-md: $f"
	if ! rustdoc --test "$f" \
		--edition "$EDITION" \
		--extern "ltk=$RLIB" \
		-L "target/debug" \
		-L "target/debug/deps" \
		--crate-name "$crate_name"
	then
		failures=$(( failures + 1 ))
	fi
done

if [ "$failures" -gt 0 ]; then
	echo "doctest-md: $failures markdown file(s) with failing snippets" >&2
	exit 1
fi

echo "doctest-md: all docs/*.md snippets compile"
