#!/bin/bash
# ci/check [--cpus N] [PYTHON]: what CI checks, the same here as on GitHub (.github/workflows/ci.yml calls it once per
# Python): ruff's pyflakes rules (unused imports and variables, undefined names, syntax 3.11 cannot read), then
# the whole test suite, journeys included.
#
#   ci/check            the suite on the python3 on PATH (pp promote's gate, in the release it is about to flip)
#   ci/check 3.11       on a uv-managed CPython 3.11, the oldest pp supports (installed by uv on first use)
#   ci/check 3.14       ... the newest CI runs
#   ci/check --cpus 2 3.11   ... on 2 CPUs (taskset) and with its own process table (unshare), like a CI runner:
#                       a test that passes only because its worker or server always gets a CPU at once, or because
#                       a scan of /proc is slow on a busy machine, fails here too
#
# pp has no dependencies; uv brings the tools CI needs: ruff (pinned) and the Pythons. A managed Python has
# nothing installed in it, so a third-party import fails here even when the shell's python3 has the package.
# Needs uv, git, sh and bash; the zsh tests skip without it.
set -euo pipefail
cd "$(dirname "$0")/.."
pin=()
if [ "${1:-}" = "--cpus" ]; then
	pin=(taskset -c "0-$(($2 - 1))")
	if unshare --map-current-user --pid --fork --mount-proc true 2>/dev/null; then
		pin=(unshare --map-current-user --pid --fork --mount-proc "${pin[@]}")
	else
		echo "ci/check: unshare cannot make a process table here; this machine's is used" >&2
	fi
	shift 2
fi
uvx ruff@0.16.9 check --quiet --no-cache --select F,E9 --target-version py311 .
py=python3
if [ -n "${1:-}" ]; then
	uv python install --quiet "$1"
	py=$(uv python find --managed-python "$1")
fi
"$py" -c 'import sys; print("ci/check: Python", sys.version.split()[0], sys.executable)'
"${pin[@]}" "$py" -m unittest discover -s tests -q
