#!/usr/bin/env bash
# CI step timing wrap — bash half (releases#108).
#
# The xtask wrap cannot be used in CI for the steps that matter: it is a cargo
# binary, and it cannot time the build that produces it. So CI has its own
# writer, and the row shape is pinned against xtask's ROW_FIELDS by
# crates/xtask/tests/bench_row_parity.rs — two writers of one format drift in
# silence otherwise, and a drifted ledger is unreadable exactly when somebody
# wants a trend across milestones.
#
# TRANSPARENT: stdio is inherited untouched and the wrapped command's exit code
# is this script's exit code. Instrumenting a step must not change what the step
# does, or the measurement has altered the thing measured.
#
# Usage: bash .github/bench/wrap.sh <step-name> -- <command> [args…]
set -uo pipefail

step="${1:?usage: wrap.sh <step-name> -- <command…>}"
shift
[ "${1:-}" = "--" ] || { echo "wrap.sh: expected -- before the command" >&2; exit 2; }
shift

ledger_dir="${BENCH_LEDGER_DIR:-bench-ledger}"
mkdir -p "$ledger_dir" 2>/dev/null || true
key="${GITHUB_SHA:-$(git rev-parse --short HEAD 2>/dev/null || echo no-key)}"
host="${RUNNER_NAME:-${HOSTNAME:-unknown-host}}"

now_ms() { python3 -c 'import time; print(int(time.time()*1000))' 2>/dev/null || date +%s000; }

t0=$(now_ms)
"$@"
rc=$?
t1=$(now_ms)

ok=false
[ "$rc" -eq 0 ] && ok=true
# One line, the declared field order. Appended, never rewritten: the ledger is
# history, and CI uploads it as a per-run artifact rather than committing it.
printf '{"step":"%s","key":"%s","host":"%s","duration_ms":%s,"ts_ms":%s,"ok":%s}\n' \
  "$step" "$key" "$host" "$((t1 - t0))" "$t1" "$ok" \
  >> "$ledger_dir/ci-$(printf '%s' "$host" | tr -c 'a-zA-Z0-9' '-').jsonl" 2>/dev/null || true

exit $rc
