#!/usr/bin/env bash
# ############################################################################
# EXECUTABLE: just-runit (alias: jbx)                                        #
# PACKAGE: just-bashit                                                       #
# ############################################################################
# Ephemeral bash tool runner. Fetch a script from a URL or namespace, call   #
# an optional function, then discard — no installation, no env pollution.    #
# Analogous to uvx but for any bash/Python script reachable over HTTPS.      #
# ############################################################################
set -euo pipefail
IFS=$'\n\t'

# ---- defaults ---------------------------------------------------------------

_CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/just-runit"
_ME="$(basename "$0")"
_VERSION="0.13.0"
_DEFAULT_TTL=3600

# Default namespace base URL (just-buildit org pages root).
_JB_DEFAULT_NS="just-buildit"
_JB_DEFAULT_BASE="https://just-buildit.github.io"

# just-bashit source base — sibling libs co-fetched for inter-lib calls.
# Served from the Pages CDN (mirror of src/just_bashit/), NOT
# raw.githubusercontent, which rate-limits shared CI runner IPs.
_JBS_BASE="https://just-buildit.github.io/jbs"

# The built-in namespaces, one row each: "NAME BASE-URL". The resolver, its
# unknown-namespace error and the help text all read this table, so a
# namespace is added in one place. just-bashit is listed for the help and the
# error only: it resolves through the co-fetch bundle, not through a base.
_NAMESPACES=(
	"just-buildit ${_JB_DEFAULT_BASE}"
	"just-bashit ${_JBS_BASE}"
	"just-makeit ${_JB_DEFAULT_BASE}/just-makeit"
)
# All src/ libs; fetched together so relative inter-source calls resolve.
_JBS_LIBS=(
	datetime environment file format
	function-template logging match network path
	pkg toml windows jbx-shell
)

# ---- bootstrap.toml ------------------------------------------------------------

# _tool_sources FILE -- every `source = "..."` value inside a [tools.*]
# section, one per line. Pure bash for the reason _lookup_alias is: jbx must
# run on a machine with no awk, since installing one is setup-system's job.
_tool_sources() {
	local line in_t=0
	local source_re='^[[:space:]]*source[[:space:]]*=[[:space:]]*"([^"]*)"'
	while IFS= read -r line || [[ -n ${line} ]]; do
		case "${line}" in
		'[tools.'*)
			in_t=1
			continue
			;;
		'['*)
			in_t=0
			continue
			;;
		*) ;;
		esac
		if [[ ${in_t} -eq 1 && ${line} =~ ${source_re} ]]; then
			printf '%s\n' "${BASH_REMATCH[1]}"
		fi
	done <"${1}"
}

# ---- portable checksums -----------------------------------------------------
# GNU coreutils' sha256sum/md5sum are absent on macOS/BSD, where the tools are
# shasum/md5 — a fetch there died with "sha256sum: command not found". Prefer
# the coreutils names, fall back to the BSD ones; both read stdin, and we emit
# only the hex digest (BSD `md5` prints the bare hash for stdin, so the same
# `cut` is harmless there).
_sha256() {
	if command -v sha256sum >/dev/null 2>&1; then
		sha256sum | cut -d' ' -f1
	else
		shasum -a 256 | cut -d' ' -f1
	fi
}

_md5() {
	if command -v md5sum >/dev/null 2>&1; then
		md5sum | cut -d' ' -f1
	else
		md5 | cut -d' ' -f1
	fi
}

# ---- top-level dispatch (when called by the full name, "just-runit") --------
#
# This triggered on "jb" and "just-buildit" until 0.5.0, and that was the root
# of a three-way collision on one token: `just-buildit` is the GitHub org, the
# PEP 517 build backend, AND — via a symlink get-jb.sh created — this runner.
# `jb`/`just-buildit` now mean the backend only, since it is the one that
# actually builds; this runner answers to `just-runit` and `jbx`.
#
# The subcommands had to move somewhere, since they were only ever reachable
# under those two names. They now live under the FULL name, and `just-runit`
# falls THROUGH to the SPEC runner when the first argument is not a known
# subcommand — so `just-runit <url>` keeps working, which is how the fetch
# tests and every existing caller invoke it.
#
# `jbx` deliberately does NOT take subcommands. That is the escape hatch: a
# script genuinely named `install` or `cache` is reachable as `jbx install`,
# unambiguously, and no SPEC is shadowed by a keyword.

if [[ ${_ME} == "just-runit" ]]; then
	SUBCMD="${1:-}"
	case "${SUBCMD}" in
	run)
		shift
		_ME="${_ME} run"
		;;
	cache)
		shift
		_CACHE_OP="${1:-}"
		case "${_CACHE_OP}" in
		clear)
			shift
			_CACHE_TARGET="${1:-all}"
			case "${_CACHE_TARGET}" in
			all)
				rm -rf "${_CACHE_DIR}"
				echo "cleared ${_CACHE_DIR}"
				;;
			jbs)
				rm -rf "${_CACHE_DIR}/jbs"
				echo "cleared ${_CACHE_DIR}/jbs"
				;;
			*)
				# Treat arg as a URL — remove its cache entry.
				_key=$(printf '%s' "${_CACHE_TARGET}" | _sha256)
				_removed=0
				for _f in "${_CACHE_DIR}/${_key}".{sh,py} "${_CACHE_DIR}/${_key}".meta; do
					[[ -f ${_f} ]] && {
						rm -f "${_f}"
						_removed=1
					}
				done
				if [[ ${_removed} -eq 1 ]]; then
					echo "cleared cache entry for ${_CACHE_TARGET}"
				else
					echo "${_ME}: no cache entry found for ${_CACHE_TARGET}" >&2
					exit 1
				fi
				;;
			esac
			;;
		"" | -h | --help)
			cat <<-EOF
				Usage: ${_ME} cache <operation> [TARGET]

				Operations:
				  clear [all]   Remove all cached scripts and aliases (default)
				  clear jbs     Remove the just-bashit co-fetch bundle only
				  clear <url>   Remove the cache entry for a specific URL
			EOF
			;;
		*)
			echo "${_ME} cache: unknown operation '${_CACHE_OP}'" >&2
			echo "Run '${_ME} cache -h' for usage." >&2
			exit 1
			;;
		esac
		exit 0
		;;
	install)
		# --no-verify reaches every fetch below, which run the runner with -f.
		_install_opts=()
		if [[ ${2:-} == --no-verify ]]; then
			_install_opts=(--no-verify)
		elif [[ -n ${2:-} ]]; then
			echo "${_ME} install: unknown argument '${2}'" >&2
			exit 1
		fi
		# Find the bootstrap manifest walking up from CWD.
		#
		# The legacy name `jb.toml` is no longer read (#30). The nearest one
		# met on the walk, before any bootstrap.toml, is REFUSED rather than
		# skipped: skipping it would install from some ancestor's manifest
		# instead of the project's own, or report none at all.
		_toml=""
		_dir="${PWD}"
		while [[ "${_dir}" != "/" ]]; do
			if [[ -f "${_dir}/bootstrap.toml" ]]; then
				_toml="${_dir}/bootstrap.toml"
				break
			fi
			if [[ -f "${_dir}/jb.toml" ]]; then
				echo "${_ME}: ${_dir}/jb.toml is no longer read, rename it: git mv jb.toml bootstrap.toml" >&2
				exit 1
			fi
			_dir="$(dirname "${_dir}")"
		done
		if [[ -z "${_toml}" ]]; then
			echo "${_ME}: no bootstrap.toml found (searched up from ${PWD})" >&2
			exit 1
		fi
		printf '  reading %s\n' "${_toml}"
		# Extract all source = "..." values from [tools.*] sections.
		mapfile -t _sources < <(_tool_sources "${_toml}")
		if [[ ${#_sources[@]} -eq 0 ]]; then
			echo "${_ME}: no [tools.*] entries with source in ${_toml}"
			exit 0
		fi
		_runner="$(readlink -f "${BASH_SOURCE[0]}")"
		_ok=0
		_fail=0
		# -f: resolve and fetch into the cache, run nothing. This used -l,
		# and -l lists functions by SOURCING the script, so every tool
		# without a main guard RAN, its output discarded -- setup-system.sh
		# among them, which this repo's own bootstrap.toml names
		# (just-bashit#117).
		for _src in "${_sources[@]}"; do
			printf '  -> %s ' "${_src}"
			if "${_runner}" "${_install_opts[@]+"${_install_opts[@]}"}" \
				-f "${_src}" >/dev/null 2>&1; then
				printf 'ok\n'
				((_ok++)) || true
			else
				printf 'failed\n' >&2
				((_fail++)) || true
			fi
		done
		printf '  %d fetched' "${_ok}"
		[[ ${_fail} -gt 0 ]] && printf ', %d failed' "${_fail}"
		printf '\n'
		[[ ${_fail} -gt 0 ]] && exit 1 || exit 0
		;;
	version | -V | --version)
		echo "${_ME} v${_VERSION}"
		exit 0
		;;
	"" | help | -h | --help)
		cat <<-EOF
			Usage: ${_ME} <command> [OPTIONS] [ARGS...]

			Commands:
			  run      Ephemeral script runner (alias: jbx)
			  install  Pre-fetch all tools declared in bootstrap.toml
			  cache    Manage the local script cache
			  version  Print version and exit

			Run '${_ME} <command> -h' for details.
		EOF
		exit 0
		;;
	*)
		# Not a subcommand, so it is a SPEC: fall through to the runner
		# below rather than erroring. This is what keeps `just-runit <url>`
		# working now that the full name owns the subcommands.
		:
		;;
	esac
fi

# ---- option state -----------------------------------------------------------

OPT_REFRESH=0
OPT_NO_CACHE=0
OPT_CLEAN=0
OPT_VERBOSE=0
OPT_LIST=0
OPT_FETCH=0
OPT_TTL="${_DEFAULT_TTL}"
OPT_CHECKSUM=""
OPT_NO_VERIFY=0
_CURL_TLS=()
OPT_PASS=()
OPTARG=""
OPTIND=1

# ---- help -------------------------------------------------------------------

# One line per built-in namespace, from the _NAMESPACES table.
_ns_help=""
for _row in "${_NAMESPACES[@]}"; do
	_ns_help+="$(printf '  %-21s %s/' "${_row%% *}" "${_row#* }")"
	[[ ${_row%% *} == "${_JB_DEFAULT_NS}" ]] && _ns_help+="   (default)"
	_ns_help+=$'\n'
done
_ns_help="${_ns_help%$'\n'}"

read -r -d '' HELP <<-EOF || true
	Usage: ${_ME} [OPTIONS] SPEC [FUNCTION [ARGS...]]
	   or: jbx [OPTIONS] SPEC [FUNCTION [ARGS...]]

	  Ephemeral tool runner. Resolve SPEC to a script, optionally call
	  FUNCTION with ARGS, then discard — no installation, no env pollution.

	SPEC forms:
	  NAME                  bare name, resolved via default namespace (just-buildit)
	  NS:NAME               explicit namespace (e.g. just-bashit:logging)
	  gh:USER/REPO/PATH     GitHub raw, default branch main
	  gh:USER/REPO/PATH@REF GitHub raw at a specific ref/tag/sha
	  https://URL           direct URL
	  [FORGE+]https://HOST[:PORT]/PROJECT//PATH[@REF]
	                        a script in a repository, by its path in the
	                        repo; REF defaults to HEAD (the default branch).
	                        FORGE: github, gitlab, gitea (forgejo), bitbucket;
	                        optional for github.com, gitlab.com, codeberg.org
	                        and bitbucket.org. Public repos only, HTTPS only.

	Namespaces:
	${_ns_help}

	Resolution order for NAME / NS:NAME:
	  1. aliases.toml at namespace base
	  2. Direct URL probe: NS_BASE/NAME.sh then NS_BASE/NAME.py

	Options:
	  -h        Show this message and exit.
	  -l        List functions defined by SPEC, and by the files it sources,
	            then exit. Nothing runs: a shell script is read, a Python
	            one parsed.
	  -f        Fetch only — cache SPEC, print its path, run nothing.
	  -r        Refresh — ignore and overwrite cached copy.
	  -n        No-cache — fetch fresh, discard on exit (cache untouched).
	  -c        Clean environment (minimal, like sudo without -E).
	  -p VARS   Comma-separated var names to pass through with -c.
	  -t TTL    Cache TTL in seconds (default 3600). 0 = keep forever.
	  -k HASH   Verify script before running: sha256:HASH or md5:HASH.
	  --no-verify
	            Skip TLS certificate checks on ${_ME}'s own downloads
	            (curl --insecure), e.g. behind a TLS-intercepting proxy.
	            Warns when used. Pair it with -k HASH so the script is
	            still verified. Downloads the script itself makes are
	            not affected.
	  -v        Verbose.

	Language detection (automatic):
	  .sh / bash shebang   Sourced into a bash subshell; FUNCTION supported.
	  .py / python shebang Run with uv run (PEP 723 inline deps) or python3.
	                       FUNCTION not supported for Python — pass args directly.

	Examples:
	  ${_ME} install-deps -s apt
	  ${_ME} just-bashit:logging log "hello"
	  ${_ME} just-makeit:install-deps
	  ${_ME} just-bashit:datetime iso-8601-basic -m
	  ${_ME} gh:user/repo/tools/deploy.sh run --env prod
	  ${_ME} gh:user/repo/tool.sh@v2.1.0 setup
	  ${_ME} https://gitlab.com/group/sub/repo//bin/tool.sh@v2 run
	  ${_ME} gitea+https://git.example.com:3000/ops/tools//deploy.sh deploy
	  ${_ME} https://example.com/tool.sh
	  ${_ME} https://example.com/tool.py --flag value
	  ${_ME} -l just-bashit:logging
	  ${_ME} -c -p HOME,TERM https://example.com/tool.sh func arg
	  ${_ME} -n -k sha256:abc123 https://example.com/tool.sh fn
EOF

# ---- parse options ----------------------------------------------------------

# --no-verify is the one long option, and getopts reads none, so it is taken
# out here first. Only the options before SPEC are scanned: an argument after
# SPEC belongs to the script, so `jbx tool.sh fn --no-verify` passes the flag
# to fn. The scan has to know which options take a value (p, t, k), so a value
# such as `-k --no-verify` is not mistaken for the flag, nor for SPEC, and the
# same for a cluster ending in one (`-nk HASH`).
_opts=()
while [[ $# -gt 0 ]]; do
	case "${1}" in
	--no-verify)
		OPT_NO_VERIFY=1
		shift
		;;
	--)
		_opts+=("${1}")
		shift
		break
		;;
	-?*)
		_opts+=("${1}")
		_cluster="${1#-}"
		shift
		# A value-taking letter consumes the rest of the cluster, or, as
		# its last letter, the next argument.
		while [[ -n ${_cluster} ]]; do
			_c="${_cluster:0:1}"
			_cluster="${_cluster:1}"
			if [[ ${_c} == [ptk] ]]; then
				if [[ -z ${_cluster} && $# -gt 0 ]]; then
					_opts+=("${1}")
					shift
				fi
				break
			fi
		done
		;;
	*) break ;;
	esac
done
set -- "${_opts[@]+"${_opts[@]}"}" "$@"

while getopts ":hlfrncvp:t:k:" option; do
	case $option in
	h)
		echo "${HELP}"
		exit 0
		;;
	l) OPT_LIST=1 ;;
	f) OPT_FETCH=1 ;;
	r) OPT_REFRESH=1 ;;
	n) OPT_NO_CACHE=1 ;;
	c) OPT_CLEAN=1 ;;
	v) OPT_VERBOSE=1 ;;
	p) IFS=',' read -ra OPT_PASS <<<"${OPTARG}" ;;
	t) OPT_TTL="${OPTARG}" ;;
	k) OPT_CHECKSUM="${OPTARG}" ;;
	\?)
		echo "Invalid option: -${OPTARG}"
		echo "${HELP}"
		exit 1
		;;
	esac
done
shift "$((OPTIND - 1))"

if [[ ${OPT_NO_VERIFY} -eq 1 ]]; then
	_CURL_TLS=(--insecure)
	echo "${_ME}: warning: --no-verify: TLS certificates are not checked" >&2
fi

[[ $# -eq 0 ]] && {
	echo "${HELP}"
	exit 1
}

RAW_SPEC="${1}"
shift
# Only treat the next arg as a function name if it doesn't look like a flag.
# Flags (starting with -) and missing args fall through to ARGS unchanged.
FUNC="${1:-}"
if [[ -n ${FUNC} && ${FUNC} != -* ]]; then
	shift || true
else
	FUNC=""
fi
ARGS=("$@")

# ---- helpers ----------------------------------------------------------------

_log() { [[ ${OPT_VERBOSE} -eq 1 ]] && echo "${_ME}: $*" >&2 || true; }
_err() {
	echo "${_ME}: error: $*" >&2
	exit 1
}

# ---- namespace resolution ---------------------------------------------------

# Parse aliases.toml from NS_BASE/aliases.toml and look up a name.
# Prints the resolved URL, or nothing when the file was read and does not list
# the name -- the one case in which the caller may fall through to the direct
# probe.
#
# A file that could not be had is never that case (just-bashit#164). Every
# built-in namespace serves an aliases.toml, so a failed fetch -- after
# _curl_get's bounded retries -- or an HTTP error is refused, naming the URL
# and curl's message. Read as "not listed" instead, a blip fetching it sent
# `jbx install-deps` to the org root's mirror copy of install-deps.sh, which
# cannot run without the libraries beside it ("toml.sh: No such file").
# What was fetched must also read as an aliases file -- it has an [aliases]
# table -- so a 200 that is not one (a captive portal, a cache written by a
# jbx without --fail) is refused too.
#
# A cached copy past its TTL is the one fallback: if the refetch fails, the
# last good copy answers, with a warning naming the URL. It was fetched and
# checked in full, so it can be out of date but not wrong, and an outdated
# alias is a valid source where the probe is not. Its timestamp is left
# alone, so the next run retries. -r and -n ask for a fresh copy, so under
# them a failed refetch is refused.
#
# Under -n the file goes to main's per-run directory, never the cache, and as
# that directory starts empty it is always fetched fresh (just-bashit#122).
_lookup_alias() {
	local base="${1}" name="${2}"
	local aliases_url="${base}/aliases.toml"
	local key
	key=$(printf '%s' "${base}" | _sha256)
	local aliases_cache="${_CACHE_DIR}/aliases-${key}.toml"
	if [[ ${OPT_NO_CACHE} -eq 1 ]]; then
		aliases_cache="${_NO_CACHE_DIR}/aliases-${key}.toml"
	fi

	if [[ ${OPT_REFRESH} -eq 1 ]] || ! _cache_valid "${aliases_cache}" ||
		! _is_aliases_file "${aliases_cache}"; then
		mkdir -p "${aliases_cache%/*}"
		_log "fetching ${aliases_url}"
		local why="" rc=0
		why=$(_curl_get "${aliases_url}" "${aliases_cache}.new" 2>&1) || rc=$?
		if [[ ${rc} -eq 0 ]] && ! _is_aliases_file "${aliases_cache}.new"; then
			rc=1 why="the response has no [aliases] table"
		fi
		if [[ ${rc} -ne 0 ]]; then
			rm -f "${aliases_cache}.new"
			why="${why//$'\n'/ }"
			why="${why:-curl exit ${rc}}"
			if [[ ${OPT_REFRESH} -eq 0 && ${OPT_NO_CACHE} -eq 0 ]] &&
				_is_aliases_file "${aliases_cache}"; then
				echo "${_ME}: warning: could not refetch ${aliases_url} (${why}); using the cached copy" >&2
			else
				_err "could not fetch ${aliases_url} (${why}); refusing to guess where '${name}' is served from"
			fi
		else
			mv "${aliases_cache}.new" "${aliases_cache}"
			printf 'ts=%s\nurl=%s\n' "$(date +%s)" "${aliases_url}" \
				>"$(_meta_path "${aliases_cache}")"
		fi
	fi

	# Parse: find key under [aliases] section. Pure bash, not awk: this is
	# the first thing `jbx setup-system` does on a new machine, and a minimal
	# Debian 13 WSL image ships no awk at all -- setup-system, which installs
	# one, could not even be resolved (2026-10-03).
	local line in_sec=0 key val
	local entry_re='^[[:space:]]*([^#=[:space:]][^=]*)=(.*)$'
	local value_re='^[[:space:]"]*(.*[^[:space:]"])[[:space:]"]*$'
	while IFS= read -r line || [[ -n ${line} ]]; do
		case "${line}" in
		'[aliases]'*)
			in_sec=1
			continue
			;;
		'['*)
			in_sec=0
			continue
			;;
		*) ;;
		esac
		[[ ${in_sec} -eq 1 && ${line} =~ ${entry_re} ]] || continue
		key="${BASH_REMATCH[1]}"
		key="${key%"${key##*[![:space:]]}"}"
		val="${BASH_REMATCH[2]}"
		if [[ ${val} =~ ${value_re} ]]; then
			val="${BASH_REMATCH[1]}"
		else
			val=""
		fi
		if [[ ${key} == "${name}" ]]; then
			printf '%s\n' "${val}"
			return 0
		fi
	done <"${aliases_cache}"
}

# _is_aliases_file FILE -- is FILE there, with an [aliases] table?
_is_aliases_file() {
	local line
	[[ -f ${1} ]] || return 1
	while IFS= read -r line || [[ -n ${line} ]]; do
		[[ ${line} == '[aliases]'* ]] && return 0
	done <"${1}"
	return 1
}

# Probe whether a URL exists (HEAD, no download).  Returns 0 if 2xx/3xx.
_head_ok() {
	local url="${1}"
	local code
	_curl_tls_init
	code=$(curl -sSL "${_CURL_TLS[@]+"${_CURL_TLS[@]}"}" --proto '=https' --tlsv1.2 --max-time 5 \
		-o /dev/null -w '%{http_code}' --head "${url}" 2>/dev/null)
	[[ ${code} == "200" || ${code} == "301" || ${code} == "302" ]]
}

# Resolve NS:NAME or bare NAME against a namespace base URL.
# Returns a URL or the internal "jbs:NAME" marker for just-bashit.
_resolve_ns() {
	local ns="${1}" name="${2}"

	# Map namespace to base URL.
	local base="" row known=""
	for row in "${_NAMESPACES[@]}"; do
		known+="${known:+, }${row%% *}"
		[[ ${row%% *} == "${ns}" ]] && base="${row#* }"
	done
	[[ -n ${base} ]] || _err "unknown namespace '${ns}'; known: ${known}"
	if [[ ${ns} == just-bashit ]]; then
		# just-bashit uses the co-fetch mechanism; return internal marker.
		echo "jbs:${name}"
		return
	fi

	# 1. Check aliases.toml first (one cached round-trip covers all names).
	local alias_url
	# `|| exit`: errexit does not reach into a command substitution, so a
	# refusal _lookup_alias made would otherwise be dropped right here.
	alias_url=$(_lookup_alias "${base}" "${name}") || exit 1
	if [[ -n ${alias_url} ]]; then
		_log "resolved '${name}' via aliases.toml -> ${alias_url}"
		echo "${alias_url}"
		return
	fi

	# 2. Probe direct .sh then .py.
	local url_sh="${base}/${name}.sh"
	local url_py="${base}/${name}.py"
	if _head_ok "${url_sh}"; then
		_log "resolved '${name}' via direct probe -> ${url_sh}"
		echo "${url_sh}"
		return
	fi
	if _head_ok "${url_py}"; then
		_log "resolved '${name}' via direct probe -> ${url_py}"
		echo "${url_py}"
		return
	fi

	_err "cannot resolve '${name}' in namespace '${ns}' (checked ${base}/aliases.toml and ${url_sh})"
}

# ---- URL resolution ---------------------------------------------------------

# Repository form (just-bashit#136): a script named by its path inside a
# repository, rather than by a host-specific raw-content URL.
#
#   [FORGE+]https://HOST[:PORT]/PROJECT//PATH[@REF]
#
# `//` separates the repository from the path, as Terraform module sources and
# go-getter do: a colon cannot, since the scheme and a port already use one,
# and no URL path holds `//` legitimately, so a plain script URL is unaffected.
# REF is a branch, tag or commit SHA, HEAD (the default branch) when omitted.
#
# FORGE names the raw-file layout. The four public hosts are known; any other
# host must say which forge serves it, because jbx does not guess a layout.
# Each layout was measured against live repositories (just-bashit#136):
#   github     raw.githubusercontent.com/O/R/REF/PATH, or HOST/O/R/raw/REF/PATH
#   gitlab     HOST/GROUP/.../PROJECT/-/raw/REF/PATH (nested groups)
#   gitea      HOST/O/R/raw/REF/PATH (Gitea, Forgejo, Codeberg)
#   bitbucket  bitbucket.org/O/R/raw/REF/PATH (Cloud only)
#
# Prints the raw HTTPS URL, which then goes through the ordinary fetch, so
# caching, -r, -n, -k and argument forwarding are unchanged. Every refusal
# names what to do instead, and none echoes credentials.
_resolve_repo() {
	local spec="${1}" forge="" rest authority host project path ref="HEAD"
	if [[ ${spec} =~ ^([a-z]+)\+([a-z][a-z0-9+.-]*://.*)$ ]]; then
		forge="${BASH_REMATCH[1]}"
		spec="${BASH_REMATCH[2]}"
	fi
	case "${forge}" in
	"" | github | gitlab | gitea | bitbucket) ;;
	forgejo) forge=gitea ;;
	*) _err "unknown forge '${forge}': use github, gitlab, gitea (or forgejo) or bitbucket" ;;
	esac
	[[ ${spec} == https://* ]] ||
		_err "a repository is fetched over HTTPS only: ${spec%%://*}:// is not supported"

	rest="${spec#https://}"
	authority="${rest%%/*}"
	rest="${rest#*/}"
	# Credentials would be written to logs and cache metadata, and jbx sends
	# none anyway: refuse them, naming the host but never the secret.
	[[ ${authority} == *@* ]] &&
		_err "credentials in a repository URL are refused (${authority##*@}): jbx fetches public repositories only"
	host="${authority%%:*}"
	[[ -n ${host} ]] || _err "no host in repository URL: ${spec}"

	project="${rest%%//*}"
	path="${rest#*//}"
	if [[ ${path} == *@* ]]; then
		ref="${path##*@}"
		path="${path%@*}"
	fi
	project="${project%/}"
	project="${project%.git}"

	if [[ -z ${forge} ]]; then
		case "${host}" in
		github.com) forge=github ;;
		gitlab.com) forge=gitlab ;;
		codeberg.org) forge=gitea ;;
		bitbucket.org) forge=bitbucket ;;
		*) _err "jbx does not know which forge serves ${authority}; name it, e.g. gitea+https://${authority}/... (github, gitlab, gitea, bitbucket)" ;;
		esac
	fi

	local -a parts
	IFS=/ read -ra parts <<<"${project}"
	local part
	for part in "${parts[@]}"; do
		[[ -n ${part} ]] || _err "empty segment in repository path '${project}'"
	done
	if [[ ${forge} == gitlab ]]; then
		[[ ${#parts[@]} -ge 2 ]] ||
			_err "a GitLab project is GROUP/.../PROJECT, not '${project}'"
	else
		[[ ${#parts[@]} -eq 2 ]] ||
			_err "a ${forge} repository is OWNER/REPO, not '${project}'"
	fi

	[[ -n ${path} && ${path} != /* ]] ||
		_err "no script path after '//' in ${spec%@*}: name the file inside the repository"
	IFS=/ read -ra parts <<<"${path}"
	for part in "${parts[@]}"; do
		[[ -n ${part} && ${part} != ".." ]] ||
			_err "bad script path '${path}': no empty or '..' segments"
	done
	[[ -n ${ref} ]] || _err "empty ref after '@' in ${spec}"
	[[ ${ref} != */* ]] ||
		_err "ref '${ref}' contains '/', which is ambiguous in a raw URL: pin a tag or commit SHA"
	[[ ${ref} =~ ^[A-Za-z0-9._-]+$ ]] || _err "bad ref '${ref}'"

	case "${forge}" in
	github)
		if [[ ${host} == github.com ]]; then
			echo "https://raw.githubusercontent.com/${project}/${ref}/${path}"
		else
			echo "https://${authority}/${project}/raw/${ref}/${path}"
		fi
		;;
	gitlab) echo "https://${authority}/${project}/-/raw/${ref}/${path}" ;;
	gitea) echo "https://${authority}/${project}/raw/${ref}/${path}" ;;
	bitbucket)
		[[ ${host} == bitbucket.org ]] ||
			_err "only Bitbucket Cloud (bitbucket.org) is supported: Server/Data Center serves raw files on another layout"
		echo "https://${authority}/${project}/raw/${ref}/${path}"
		;;
	esac
}

_resolve() {
	local raw="${1}"
	case "${raw}" in
	just-bashit:*)
		# Explicit just-bashit namespace; use co-fetch mechanism.
		echo "jbs:${raw#just-bashit:}"
		;;
	[a-z]*+*://* | *://*/*//*)
		# A repository and a path inside it (just-bashit#136).
		_resolve_repo "${raw}"
		;;
	*@*:*//*)
		_err "SSH repository URLs are not supported; use the HTTPS form: [FORGE+]https://HOST/PROJECT//PATH"
		;;
	*://*)
		case "${raw}" in
		https://*) echo "${raw}" ;;
		http://*) _err "HTTP not allowed; use HTTPS" ;;
		*) _err "unrecognised URL scheme: ${raw}" ;;
		esac
		;;
	gh:*)
		local spec="${raw#gh:}" ref="main"
		if [[ ${spec} == *@* ]]; then
			ref="${spec##*@}"
			spec="${spec%@*}"
		fi
		local user repo path
		user="${spec%%/*}"
		spec="${spec#*/}"
		repo="${spec%%/*}"
		path="${spec#*/}"
		echo "https://raw.githubusercontent.com/${user}/${repo}/${ref}/${path}"
		;;
	*:*)
		# NS:NAME form (not a URL scheme — no :// present).
		local ns="${raw%%:*}" name="${raw#*:}"
		_resolve_ns "${ns}" "${name}"
		;;
	*)
		# Bare name — resolve against default namespace.
		_resolve_ns "${_JB_DEFAULT_NS}" "${raw}"
		;;
	esac
}

# ---- cache helpers ----------------------------------------------------------

_cache_key() { printf '%s' "${1}" | _sha256; }

_cache_ext() { case "${1}" in *.py) echo ".py" ;; *) echo ".sh" ;; esac }

_cache_path() {
	local url="${1}"
	echo "${_CACHE_DIR}/$(_cache_key "${url}")$(_cache_ext "${url}")"
}

_meta_path() { echo "${1%.*}.meta"; }

_cache_valid() {
	local cached="${1}"
	[[ -f ${cached} ]] || return 1
	local meta
	meta=$(_meta_path "${cached}")
	[[ -f ${meta} ]] || return 1
	[[ ${OPT_TTL} -eq 0 ]] && return 0
	local ts now
	ts=$(grep '^ts=' "${meta}" | cut -d= -f2)
	now=$(date +%s)
	((now - ts < OPT_TTL))
}

# Retry flags the curl at hand actually understands. `--retry-all-errors` needs
# curl >= 7.71, but enterprise LTS bases — RHEL/Oracle/Rocky/Alma 8, a large
# slice of downstream consumers — ship 7.61, where an unknown flag aborts the
# whole fetch ("option --retry-all-errors: is unknown"). `--retry` and
# `--retry-connrefused` (>= 7.52) already ride out timeouts and 429/5xx
# throttling there; `--retry-all-errors` is added only where curl accepts it, so
# the bootstrap stays dependable from curl 7.61 through current. Probed once.
#
# Populated as an ARRAY, not a space-joined string: this file runs under the
# strict `IFS=$'\n\t'` set at the top, so an unquoted `$(...)` of a
# space-separated string would NOT word-split — curl would see the whole
# "--retry 3 --retry-connrefused ..." as one bogus option and abort every
# fetch. `"${_CURL_RETRY_OPTS[@]}"` expands to distinct args regardless of IFS.
_curl_retry_opts_init() {
	if [[ -z ${_CURL_RETRY_OPTS+x} ]]; then
		_CURL_RETRY_OPTS=(--retry 3 --retry-connrefused)
		if curl --retry-all-errors --help >/dev/null 2>&1; then
			_CURL_RETRY_OPTS+=(--retry-all-errors)
		fi
	fi
}

# _curl_tls_init -- the TLS options every curl fetch passes, in _CURL_TLS:
# --ssl-revoke-best-effort on a Schannel curl (Git for Windows), so an
# unreachable OCSP/CRL endpoint is not a failed install. A COPY of pkg.sh's,
# which is canonical and says why; jbx sources no library of its own.
# test/curl-tls.bats holds this body byte-identical to it.
_curl_tls_init() {
	local v=''
	if [[ -n ${_CURL_TLS_SET-} ]]; then
		return 0
	fi
	_CURL_TLS_SET=1
	read -r v < <(curl -V 2>/dev/null) || :
	if [[ ${v} =~ Schannel ]]; then
		_CURL_TLS+=(--ssl-revoke-best-effort)
	fi
}

# _curl_get URL DEST -- the one bounded, fail-closed download every fetch
# makes: --fail, so an HTTP error is a failure and no error body reaches DEST,
# and the probed retry flags above, so a transient blip is retried a bounded
# number of times. Returns curl's exit status; curl's own message (-sS) goes
# to stderr. A caller decides what a failure means.
_curl_get() {
	_curl_retry_opts_init
	_curl_tls_init
	curl -sSL --fail --proto '=https' --tlsv1.2 "${_CURL_TLS[@]+"${_CURL_TLS[@]}"}" \
		"${_CURL_RETRY_OPTS[@]}" --connect-timeout 30 \
		-o "${2}" "${1}"
}

_fetch_to() {
	local url="${1}" dest="${2}"
	_log "fetching ${url}"
	# Fail closed. Without --fail, curl writes an HTTP error body — a 404 page,
	# or a rate-limit response from raw.githubusercontent on the shared CI
	# runner IPs — into ${dest} and exits 0; jbx then executes the error page
	# as the script ("line 1: 400: command not found"). --fail emits no body
	# and returns non-zero on >=400, and the retries ride out transient
	# throttling so a blip retries instead of reddening the build.
	if ! _curl_get "${url}" "${dest}"; then
		rm -f "${dest}"
		_err "fetch failed (no usable response from ${url})"
	fi
	printf 'ts=%s\nurl=%s\n' "$(date +%s)" "${url}" >"$(_meta_path "${dest}")"
}

# ---- acquire script ---------------------------------------------------------

# For just-bashit scripts, all src/ libs are co-fetched into cache/jbs/ so
# that relative inter-source calls (e.g. logging.sh -> format.sh) resolve.
#
# Under -n the bundle goes to jbs/ inside main's per-run directory instead,
# which starts empty, so it is always fetched fresh: the siblings still
# resolve beside the script, and main's EXIT trap removes them. This path is
# taken before _acquire's own -n branch, so it ignored -n and wrote, or
# reused, the cached bundle (just-bashit#122).
_acquire_jbs() {
	local lib="${1}"
	local jbs_dir="${_CACHE_DIR}/jbs"
	[[ ${OPT_NO_CACHE} -eq 1 ]] && jbs_dir="${_NO_CACHE_DIR}/jbs"
	mkdir -p "${jbs_dir}"

	local needs_fetch=0
	local dest="${jbs_dir}/${lib}.sh"

	[[ ${OPT_REFRESH} -eq 1 ]] && needs_fetch=1
	[[ ! -f ${dest} ]] && needs_fetch=1
	! _cache_valid "${dest}" && needs_fetch=1

	if [[ ${needs_fetch} -eq 1 ]]; then
		_log "fetching all jbs libs to ${jbs_dir}"
		for l in "${_JBS_LIBS[@]}"; do
			_fetch_to "${_JBS_BASE}/${l}.sh" "${jbs_dir}/${l}.sh"
		done
		# fetch the target itself when it is not one of the core libs
		if ! printf '%s\n' "${_JBS_LIBS[@]}" | grep -qx "${lib}"; then
			_fetch_to "${_JBS_BASE}/${lib}.sh" "${dest}"
		fi
	else
		_log "cache hit: ${dest}"
	fi

	echo "${dest}"
}

_acquire() {
	local url="${1}"

	if [[ ${url} == jbs:* ]]; then
		_acquire_jbs "${url#jbs:}"
		return
	fi

	# Scripts fetched directly from _JBS_BASE need their sibling libs available
	# at ${_SCRIPT_DIR}/ (where _SCRIPT_DIR = dirname of the cached file).
	# Route through _acquire_jbs so all libs land together in cache/jbs/.
	if [[ ${url} == "${_JBS_BASE}/"* ]]; then
		local _lib="${url#"${_JBS_BASE}"/}"
		_acquire_jbs "${_lib%.sh}"
		return
	fi

	local file
	# -n: into the directory main made, which main's EXIT trap removes. A
	# trap set HERE belongs to the $(...) subshell every caller runs this
	# in, and fired as the substitution returned: the script was deleted
	# before it ran (just-bashit#118).
	if [[ ${OPT_NO_CACHE} -eq 1 ]]; then
		file="${_NO_CACHE_DIR}/script$(_cache_ext "${url}")"
		_fetch_to "${url}" "${file}"
	else
		mkdir -p "${_CACHE_DIR}"
		file=$(_cache_path "${url}")
		if [[ ${OPT_REFRESH} -eq 1 ]] || ! _cache_valid "${file}"; then
			_fetch_to "${url}" "${file}"
		else
			_log "cache hit: ${file}"
		fi
	fi

	# A just-bashit script the org serves outside _JBS_BASE runs only beside
	# its libraries, which a lone fetch never brings. The org root keeps a
	# byte-identical copy of install-deps.sh for anyone who hardcoded its URL
	# (just-buildit.github.io mirror.yml); fetched by itself it dies on its
	# first line, `source "${_SCRIPT_DIR}/toml.sh"` (just-bashit#164). So a
	# script there that sources one of _JBS_LIBS from its own directory is
	# run as what it is, through the co-fetch, from _JBS_BASE. Scoped to the
	# org's own pages: a script elsewhere is its author's, and jbx does not
	# second-guess its layout.
	local rest="${url#"${_JB_DEFAULT_BASE}"/}"
	if [[ ${url} == "${_JB_DEFAULT_BASE}/"*.sh && ${rest} != */* ]] &&
		_sources_jbs_lib "${file}"; then
		_log "${url} is a just-bashit script; co-fetching it from ${_JBS_BASE}"
		_acquire_jbs "${rest%.sh}"
		return
	fi

	echo "${file}"
}

# _sources_jbs_lib FILE -- does FILE source one of _JBS_LIBS from a directory
# variable, as `source "${_SCRIPT_DIR}/toml.sh"`? That is how a just-bashit
# script reaches the siblings it is shipped beside.
_sources_jbs_lib() {
	local line lib
	local re='^[[:space:]]*(source|\.)[[:space:]]+"\$\{[A-Za-z_][A-Za-z0-9_]*\}/([A-Za-z0-9_-]+)\.sh"'
	while IFS= read -r line || [[ -n ${line} ]]; do
		[[ ${line} =~ ${re} ]] || continue
		for lib in "${_JBS_LIBS[@]}"; do
			[[ ${BASH_REMATCH[2]} == "${lib}" ]] && return 0
		done
	done <"${1}"
	return 1
}

# ---- checksum ---------------------------------------------------------------

_verify() {
	local file="${1}" spec="${2}"
	local algo="${spec%%:*}" expected="${spec#*:}" actual
	case "${algo}" in
	sha256) actual=$(_sha256 <"${file}") ;;
	md5) actual=$(_md5 <"${file}") ;;
	*) _err "unsupported checksum algorithm: ${algo}" ;;
	esac
	[[ ${actual} == "${expected}" ]] ||
		_err "checksum mismatch (got ${actual}, expected ${expected})"
	_log "checksum OK"
}

# ---- language detection -----------------------------------------------------

# Check shebang first, fall back to URL extension.
_detect_lang() {
	local script="${1}" url="${2}"
	local shebang
	shebang=$(head -1 "${script}" 2>/dev/null || true)
	case "${shebang}" in
	*python*)
		echo "python"
		return
		;;
	esac
	case "${url}" in
	*.py)
		echo "python"
		return
		;;
	esac
	echo "bash"
}

# ---- list functions ---------------------------------------------------------

# _scan_defs FILE -- what FILE's top level defines, read and never run:
# "F<TAB>NAME" for each function it defines and "S<TAB>LINE<TAB>ARG" for
# each file it sources (ARG as written), one per line on stdout. A construct
# it cannot read to the end -- one still open at end of file, a stray ) --
# is "E<TAB>LINE<TAB>WHY", and it exits 1.
#
# This is how -l lists a script (_list_fns). -l used to SOURCE the script
# and diff the functions before and after, so listing ran the script's top
# level: in full, until -l learned to refuse a top level that runs a command
# (just-bashit#121), and its command substitutions even then -- `X=$(cmd)`
# is an assignment, and the assignment ran cmd (just-bashit#143). Reading
# runs nothing, so -l lists any script, main guard or not.
#
# Seen at the top level, and inside a top-level if (its condition and its
# branches): `name() {`, `name ()`, `function name {` and `function
# name()`, with any compound body, and `source FILE` / `. FILE`. Anything
# deeper -- a function body, a loop, a case, a { } or ( ) group -- defines
# nothing when the file is sourced unless it runs, and is skipped.
#
# It is a lexer, not a line matcher, because a function body ends at the
# brace that closes it and nowhere else: it tracks quotes, ${...}, $(...),
# $((...)), backticks, heredocs (bodies skipped, `<<-` tab-stripped),
# [[ ]], case patterns and the if/case/loop/brace/paren nesting, so a `}`
# or `fi` inside a string or a heredoc closes nothing. Pure bash, for the
# reason _lookup_alias is.
_scan_defs() {
	local LC_ALL=C
	local line="" c nx rest top d ch q
	local -i lno=0 i=0 n=0 sp=0 j=0 strip=0
	# The context stack, and per-entry state: a case's "seen in" and "in
	# pattern position", an arithmetic context's paren depth, and the word
	# state a $(...) saves and puts back.
	local -a st=() cin=() cpat=() ard=() tk=() tkl=() tkt=() tkr=() hd=()
	local -a hdp=()
	local -a s_cur=() s_taint=() s_wcmd=() s_cmd=() s_nw=() s_pop=()
	local -a s_fnhdr=() s_fnkw=() s_redir=() s_wline=() s_wtext=()
	# The word being read: its text, whether quoting or an expansion makes
	# it unable to be a reserved word (taint), and whether it began in
	# command position (wcmd). cmd: the next word is in command position.
	# nw: words so far in this simple command. pop: an && / || / | is
	# waiting for its right side. fnhdr / fnkw: a function header is
	# waiting for its body / for its name.
	local cur="" wtext="" etext=""
	local -i taint=0 wcmd=0 cmd=1 nw=0 pop=0 fnhdr=0 fnkw=0 redir=0
	local -i cont=0 wline=0 eline=0 nonif=0
	local OPEN=$'\x1e' CLOSE=$'\x1f' PH=$'\x1d'
	local ordre="^[^[:space:]#\\\\'\"\`\$<>&|;()]+"

	while IFS= read -r line || [[ -n ${line} ]]; do
		lno+=1
		if ((${#hd[@]})); then
			d="${line}"
			if [[ ${hd[0]:0:1} == 1 ]]; then
				while [[ ${d} == $'\t'* ]]; do d="${d#$'\t'}"; done
			fi
			[[ ${d} == "${hd[0]:1}" ]] && hd=("${hd[@]:1}")
			continue
		fi
		i=0
		n=${#line}
		while ((i < n)); do
			c="${line:i:1}"
			top=""
			((sp)) && top="${st[sp - 1]}"
			case "${top}" in
			SQ)
				rest="${line:i}"
				if [[ ${rest} == *"'"* ]]; then
					rest="${rest%%"'"*}"
					i+=${#rest}+1
					_tl_pop
				else
					i=n
				fi
				continue
				;;
			AQ | BT)
				q="'"
				[[ ${top} == BT ]] && q='`'
				if [[ ${c} == "\\" ]]; then
					i+=2
				elif [[ ${c} == "${q}" ]]; then
					i+=1
					_tl_pop
				else
					i+=1
				fi
				continue
				;;
			DQ | PE | AR | AP)
				_tl_inner || return 1
				continue
				;;
			esac
			# Code: the top level, a { } / ( ) group, a function body, an
			# if / case / loop, a $(...), or a [[ ]].
			nx="${line:i+1:1}"
			case "${c}" in
			' ' | $'\t')
				_tl_endword
				i+=1
				;;
			'#')
				if [[ -z ${cur} ]]; then
					i=n
				else
					cur+="${c}"
					i+=1
				fi
				;;
			"\\")
				if ((i + 1 >= n)); then
					cont=1
					i=n
				else
					_tl_wchar "${PH}"
					i+=2
				fi
				;;
			"'" | '"' | '`')
				_tl_wchar "${PH}"
				case "${c}" in
				"'") _tl_push SQ ;;
				'"') _tl_push DQ ;;
				*) _tl_push BT ;;
				esac
				i+=1
				;;
			'$')
				case "${nx}" in
				'(' | '{' | "'")
					_tl_wchar "${PH}"
					_tl_dollar
					;;
				*)
					_tl_wchar '$'
					i+=1
					;;
				esac
				;;
			'<' | '>' | '&' | '|' | ';' | '(' | ')')
				# Inside [[ ]] these are its own operators: they end a
				# word, and the word may be the ]] that closes it.
				[[ ${top} == DB ]] && _tl_endword
				if ((sp)) && [[ ${st[sp - 1]} == DB ]]; then
					i+=1
				else
					_tl_op || return 1
				fi
				;;
			*)
				if [[ ${line:i} =~ ${ordre} ]]; then
					_tl_wchar "${BASH_REMATCH[0]}"
					i+=${#BASH_REMATCH[0]}
				else
					_tl_wchar "${c}"
					i+=1
				fi
				;;
			esac
		done
		# End of line: a newline, unless escaped or inside a quote.
		if ((cont)); then
			cont=0
		else
			top=""
			((sp)) && top="${st[sp - 1]}"
			case "${top}" in
			SQ | AQ | BT | DQ | PE | AR | AP) ;;
			DB)
				# A [[ ]] may span lines, so a newline inside one is not a
				# separator. But when the line's last word is the ]] that
				# closes it, the newline after it IS one: without it the
				# next line's `}` read as an argument, and a function whose
				# body ended in `[[ ... ]]` never closed (just-bashit#132's
				# `_certs_have_updater`).
				_tl_endword
				top=""
				((sp)) && top="${st[sp - 1]}"
				if [[ ${top} != DB ]]; then
					_tl_sep nl || return 1
				fi
				;;
			*) _tl_sep nl || return 1 ;;
			esac
		fi
		if ((${#hdp[@]})); then
			hd+=("${hdp[@]}")
			hdp=()
		fi
	done <"${1}"

	_tl_endword
	if ((sp || ${#hd[@]})); then
		((${#tk[@]})) || eline=lno
		printf 'E\t%s\tunterminated at end of file: %s\n' "${eline}" \
			"${etext%"${etext##*[![:space:]]}"}"
		return 1
	fi
	_tl_collect
}

# The helpers below are _scan_defs's: they read and write its locals.

# nonif counts the open contexts that are not an if: the judge sees
# inside a top-level if, whose branches must declare too, and nothing
# deeper.
_tl_push() {
	st[sp]="${1}"
	sp=$((sp + 1))
	[[ ${1} == IF ]] || nonif=$((nonif + 1))
}

_tl_pop() {
	sp=$((sp - 1))
	[[ ${st[sp]} == IF ]] || nonif=$((nonif - 1))
	unset 'st[sp]'
}

# _tl_wchar TEXT -- append TEXT to the word, starting one if none is open.
_tl_wchar() {
	if [[ -z ${cur} ]]; then
		wcmd=cmd
		wline=lno
		wtext="${line:i}"
	fi
	[[ ${1} == "${PH}" || ${1} == "\\"* ]] && taint=1
	cur+="${1}"
}

_tl_emit() {
	((nonif == 0)) || return 0
	if ((${#tk[@]} == 0)); then
		eline=wline
		etext="${wtext}"
	fi
	tk+=("${1}")
	tkl+=("${wline}")
	tkt+=("${wtext}")
	# The word as written, while it is still on the line it began on: the
	# text from its start to here. A word spanning lines has none.
	if ((wline == lno)); then
		tkr+=("${wtext:0:${#wtext}-(n - i)}")
	else
		tkr+=("")
	fi
}

# _tl_open TYPE TOKEN / _tl_close TOKEN -- enter and leave a compound
# command. At the top level the pair is all the judge sees of it: what is
# inside is never a top-level command.
_tl_open() {
	_tl_emit "${OPEN}${2}"
	_tl_push "${1}"
	cmd=1
	nw=0
	pop=0
	fnhdr=0
}

_tl_close() {
	_tl_pop
	_tl_emit "${CLOSE}${1}"
	cmd=0
}

# _tl_mark -- note where a word-less token (an opening paren) starts.
_tl_mark() {
	wline=lno
	wtext="${line:i}"
}

_tl_endword() {
	[[ -n ${cur} ]] || return 0
	local w="${cur}" top=""
	local -i plain=$((!taint)) atcmd=wcmd
	cur=""
	taint=0
	((sp)) && top="${st[sp - 1]}"
	if ((redir)); then
		redir=0
		_tl_emit "${w}"
		return 0
	fi
	if ((plain)); then
		if [[ ${top} == DB ]]; then
			[[ ${w} == ']]' ]] && _tl_close ']]'
			return 0
		fi
		if [[ ${top} == CASE ]]; then
			if ((cin[sp - 1] == 0)) && [[ ${w} == in ]]; then
				cin[sp - 1]=1
				cpat[sp - 1]=1
				return 0
			fi
			if ((cpat[sp - 1])) && [[ ${w} == "esac" ]]; then
				_tl_close "esac"
				return 0
			fi
		fi
		if ((fnkw)); then
			fnkw=0
			fnhdr=1
			cmd=1
			_tl_emit "${w}"
			return 0
		fi
		if ((atcmd)); then
			case "${w}" in
			'{')
				_tl_open B '{'
				return 0
				;;
			'}')
				if [[ ${top} == B ]]; then
					_tl_close '}'
					return 0
				fi
				;;
			if)
				_tl_open IF if
				return 0
				;;
			then | do)
				cmd=1
				_tl_emit ';'
				return 0
				;;
			else | elif)
				cmd=1
				_tl_emit ';'
				return 0
				;;
			"fi" | "done" | "esac")
				if [[ ${top} == IF && ${w} == "fi" ||
					${top} == LOOP && ${w} == "done" ||
					${top} == CASE && ${w} == "esac" ]]; then
					_tl_close "${w}"
					return 0
				fi
				;;
			case)
				_tl_open CASE case
				cin[sp - 1]=0
				cpat[sp - 1]=0
				cmd=0
				return 0
				;;
			while | until | for | select)
				_tl_open LOOP "${w}"
				[[ ${w} == for || ${w} == select ]] && cmd=0
				return 0
				;;
			'[[')
				_tl_open DB '[['
				return 0
				;;
			function)
				fnkw=1
				_tl_emit function
				return 0
				;;
			'!' | time)
				_tl_emit "${w}"
				return 0
				;;
			esac
		fi
	fi
	_tl_emit "${w}"
	cmd=0
	nw=$((nw + 1))
	pop=0
	fnhdr=0
}

# _tl_sep KIND -- a newline (nl), `;` or `&`: the end of a command, and of a
# top-level one when nothing is open.
_tl_sep() {
	_tl_endword
	if [[ ${1} == nl ]] && ((fnhdr || pop)); then
		return 0
	fi
	cmd=1
	nw=0
	pop=0
	if ((sp == 0)); then
		_tl_collect
		tk=()
		tkl=()
		tkt=()
		tkr=()
	else
		_tl_emit ';'
	fi
	return 0
}

# _tl_save / _tl_restore -- a $(...) or <(...) reads words of its own; the
# word it sits in carries on after it.
_tl_save() {
	s_cur[sp]="${cur}"
	s_taint[sp]=taint
	s_wcmd[sp]=wcmd
	s_cmd[sp]=cmd
	s_nw[sp]=nw
	s_pop[sp]=pop
	s_fnhdr[sp]=fnhdr
	s_fnkw[sp]=fnkw
	s_redir[sp]=redir
	s_wline[sp]=wline
	s_wtext[sp]="${wtext}"
	_tl_push CS
	cur=""
	taint=0
	cmd=1
	nw=0
	pop=0
	fnhdr=0
	fnkw=0
	redir=0
}

_tl_restore() {
	_tl_pop
	cur="${s_cur[sp]}"
	taint=$((s_taint[sp]))
	wcmd=$((s_wcmd[sp]))
	cmd=$((s_cmd[sp]))
	nw=$((s_nw[sp]))
	pop=$((s_pop[sp]))
	fnhdr=$((s_fnhdr[sp]))
	fnkw=$((s_fnkw[sp]))
	redir=$((s_redir[sp]))
	wline=$((s_wline[sp]))
	wtext="${s_wtext[sp]}"
}

# _tl_dollar -- $( $(( ${ $' at line[i]: enter it.
_tl_dollar() {
	case "${line:i+1:1}" in
	'(')
		if [[ ${line:i+2:1} == '(' ]]; then
			_tl_push AR
			ard[sp - 1]=0
			i+=3
		else
			_tl_save
			i+=2
		fi
		;;
	'{')
		_tl_push PE
		i+=2
		;;
	"'")
		_tl_push AQ
		i+=2
		;;
	esac
}

# _tl_inner -- one step inside "...", ${...}, $((...)) or an array's ( ).
_tl_inner() {
	local re
	case "${top}" in
	DQ) re="^[^\\\\\"\`\$]+" ;;
	PE) re="^[^\\\\\"'\`\$}]+" ;;
	AR) re="^[^()\\\\\"'\`\$]+" ;;
	AP) re="^[^()\\\\\"'\`\$#]+" ;;
	esac
	if [[ ${line:i} =~ ${re} ]]; then
		i+=${#BASH_REMATCH[0]}
		return 0
	fi
	case "${c}" in
	"\\") i+=2 ;;
	'"')
		if [[ ${top} == DQ ]]; then
			_tl_pop
		else
			_tl_push DQ
		fi
		i+=1
		;;
	"'")
		# Literal inside "...${x:-'}"...; a quote anywhere else here.
		if [[ ${top} == PE && ${st[sp - 2]:-} == DQ ]]; then
			:
		else
			_tl_push SQ
		fi
		i+=1
		;;
	'`')
		_tl_push BT
		i+=1
		;;
	'$')
		case "${line:i+1:1}" in
		'(' | '{' | "'") _tl_dollar ;;
		*) i+=1 ;;
		esac
		;;
	'}')
		_tl_pop
		i+=1
		;;
	'#')
		# A comment in an array, when it starts a word.
		if ((i == 0)) || [[ ${line:i-1:1} == [[:space:]\(] ]]; then
			i=n
		else
			i+=1
		fi
		;;
	'(')
		if [[ ${top} == AR ]]; then
			ard[sp - 1]=$((ard[sp - 1] + 1))
		else
			_tl_push AP
		fi
		i+=1
		;;
	')')
		if [[ ${top} == AR ]] && ((ard[sp - 1] > 0)); then
			ard[sp - 1]=$((ard[sp - 1] - 1))
			i+=1
		elif [[ ${top} == AR ]]; then
			_tl_pop
			i+=1
			[[ ${line:i:1} == ')' ]] && i+=1
		else
			_tl_pop
			i+=1
		fi
		;;
	*) i+=1 ;;
	esac
	return 0
}

# _tl_op -- < > & | ; ( ) in code: redirections, heredocs, operators,
# separators, groups, function headers and case patterns.
_tl_op() {
	local top="" ahead
	((sp)) && top="${st[sp - 1]}"
	local -i patpos=0
	[[ ${top} == CASE ]] && ((cpat[sp - 1])) && patpos=1
	case "${c}" in
	'<' | '>')
		if [[ ${nx} == '(' ]]; then
			# <(...) / >(...): a command substitution inside a word.
			_tl_wchar "${PH}"
			_tl_save
			i+=2
		elif [[ ${c}${nx} == '<<' && ${line:i+2:1} != '<' ]]; then
			_tl_heredoc
		else
			# A redirection: [N]op target, kept as one word.
			[[ ${cur} =~ ^[0-9]+$ ]] || _tl_endword
			[[ -n ${cur} ]] || _tl_mark
			while [[ ${line:i:1} == [\<\>\&\|] ]]; do
				cur+="${line:i:1}"
				i+=1
			done
			while [[ ${line:i:1} == [[:blank:]] ]]; do i+=1; done
			wcmd=0
			redir=1
		fi
		;;
	'&')
		if [[ ${nx} == '&' ]]; then
			_tl_pipe '&&'
		elif [[ ${nx} == '>' ]]; then
			_tl_endword
			_tl_mark
			cur='&'
			i+=1
			c='>'
			nx="${line:i+1:1}"
			_tl_op
		else
			i+=1
			_tl_sep '&' || return 1
		fi
		;;
	'|')
		if ((patpos)); then
			_tl_endword
			i+=1
		elif [[ ${nx} == '|' || ${nx} == '&' ]]; then
			_tl_pipe "|${nx}"
		else
			_tl_pipe '|'
		fi
		;;
	';')
		if [[ ${top} == CASE && (${nx} == ';' || ${nx} == '&') ]]; then
			_tl_endword
			i+=2
			[[ ${line:i:1} == '&' ]] && i+=1
			cpat[sp - 1]=1
			cmd=0
		else
			i+=1
			_tl_sep ';' || return 1
		fi
		;;
	'(')
		ahead="${line:i+1}"
		ahead="${ahead#"${ahead%%[![:blank:]]*}"}"
		if ((patpos)) && [[ -z ${cur} ]]; then
			i+=1
		elif [[ -n ${cur} ]]; then
			if ((!taint && wcmd)) && [[ ${ahead} == ')'* && ${cur} != *=* ]]; then
				# name() -- a function header. Not `arr=()`, an empty
				# array: read as a header, it joined the next line's
				# command to it, and hid the function that line defines.
				cur+='()'
				i+=1
				while [[ ${line:i:1} != ')' ]]; do i+=1; done
				i+=1
				_tl_emit "${cur}"
				cur=""
				fnkw=0
				fnhdr=1
				cmd=1
			else
				# arr=( ... ), or an extglob @( ... ): part of the word.
				_tl_wchar "${PH}"
				_tl_push AP
				i+=1
			fi
		elif ((nw == 1 || fnhdr)) && [[ ${ahead} == ')'* ]]; then
			# name () -- a function header, spaced.
			i+=1
			while [[ ${line:i:1} != ')' ]]; do i+=1; done
			i+=1
			_tl_emit '()'
			fnhdr=1
			cmd=1
		elif [[ ${nx} == '(' ]]; then
			# (( ... )) -- arithmetic, at any position (`for ((`).
			_tl_mark
			_tl_emit "${OPEN}(("
			_tl_emit "${CLOSE}))"
			_tl_push AR
			ard[sp - 1]=0
			i+=2
		elif ((cmd)); then
			_tl_mark
			_tl_open P '('
			i+=1
		else
			_tl_wchar "${PH}"
			_tl_push AP
			i+=1
		fi
		;;
	')')
		if ((patpos)); then
			_tl_endword
			cpat[sp - 1]=0
			cmd=1
			nw=0
			i+=1
		elif [[ ${top} == P ]]; then
			_tl_endword
			i+=1
			_tl_close ')'
		elif [[ ${top} == CS ]]; then
			_tl_endword
			i+=1
			_tl_restore
		else
			printf 'E\t%s\tunbalanced ): %s\n' "${lno}" "${line}"
			return 1
		fi
		;;
	esac
	return 0
}

# _tl_pipe OP -- && || | |&: the command goes on past it.
_tl_pipe() {
	_tl_endword
	_tl_emit "${1}"
	i+=${#1}
	cmd=1
	nw=0
	pop=1
}

# _tl_heredoc -- << or <<- at line[i]: queue its delimiter; the body starts
# on the next line and is skipped there.
_tl_heredoc() {
	_tl_endword
	_tl_mark
	strip=0
	j=$((i + 2))
	if [[ ${line:j:1} == - ]]; then
		strip=1
		j+=1
	fi
	while [[ ${line:j:1} == [[:blank:]] ]]; do j+=1; done
	d=""
	q=""
	while ((j < n)); do
		ch="${line:j:1}"
		if [[ -n ${q} ]]; then
			if [[ ${ch} == "${q}" ]]; then
				q=""
			else
				d+="${ch}"
			fi
		else
			case "${ch}" in
			"'" | '"') q="${ch}" ;;
			"\\")
				j+=1
				d+="${line:j:1}"
				;;
			[[:space:]] | ';' | '&' | '|' | '<' | '>' | '(' | ')') break ;;
			*) d+="${ch}" ;;
			esac
		fi
		j+=1
	done
	hdp+=("${strip}${d}")
	_tl_emit '<<'
	i=j
}

# _tl_collect -- the top-level command in tk[]: print each function it
# defines as "F<TAB>NAME", and each file it sources as "S<TAB>LINE<TAB>ARG",
# ARG as written. It looks at every command of an && / || / | list and of a
# top-level if's condition and branches -- the tokens split at ; then elif
# else and fi -- and at nothing deeper: a function body, a loop or a case
# defines nothing when the file is sourced unless it runs.
_tl_collect() {
	local -i nt=${#tk[@]} k=0 at=0
	local t name
	for ((k = 0; k < nt; k++)); do
		# A command starts at the list's start or just past a separator.
		if ((k)); then
			case "${tk[k - 1]}" in
			'&&' | '||' | '|' | '|&' | ';' | '!' | time | "${OPEN}if" | \
				"${CLOSE}fi") ;;
			*) continue ;;
			esac
		fi
		t="${tk[k]}"
		name=""
		# function NAME [()] BODY, NAME() BODY, NAME () BODY
		if [[ ${t} == function ]]; then
			name="${tk[k + 1]:-}"
			at=$((k + 2))
			[[ ${tk[at]:-} == '()' ]] && at=$((at + 1))
		elif [[ ${t} == *'()' ]]; then
			name="${t}"
			at=$((k + 1))
		elif [[ ${tk[k + 1]:-} == '()' ]]; then
			name="${t}"
			at=$((k + 2))
		fi
		name="${name%'()'}"
		if [[ -n ${name} && ${name} != *[=${PH}]* &&
			${tk[at]:-} == "${OPEN}"* ]]; then
			printf 'F\t%s\n' "${name}"
		elif [[ ${t} == source || ${t} == . ]] && ((k + 1 < nt)) &&
			[[ ! ${tk[k + 1]} =~ ^[0-9]*\&?[\<\>] ]]; then
			printf 'S\t%s\t%s\n' "${tkl[k + 1]}" "${tkr[k + 1]}"
		fi
	done
}

# _list_fns SCRIPT LANG SPEC -- print the functions SCRIPT defines, one per
# line, sorted. Nothing in SCRIPT runs: Python is parsed (ast), and anything
# else is read as bash by _scan_defs. The functions SCRIPT gets from the
# files it sources are listed too, read the same way (_list_defs).
_list_fns() {
	local script="${1}" lang="${2}" spec="${3}"
	if [[ ${lang} == "python" ]]; then
		python3 - "${script}" <<'PYEOF'
import ast, sys
src = open(sys.argv[1]).read()
names = sorted(
    node.name
    for node in ast.walk(ast.parse(src))
    if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
)
print('\n'.join(names))
PYEOF
		return
	fi
	local -A seen=()
	local -a names=()
	local bad=""
	if ! _list_defs "${script}"; then
		_err "-l cannot read ${spec}: line ${bad%%$'\t'*} of ${script}:" \
			"${bad#*$'\t'}"
	fi
	((${#names[@]})) || return 0
	printf '%s\n' "${names[@]}" | sort -u
}

# _list_defs FILE -- add the functions FILE defines to _list_fns's names[],
# then those of each file it sources, once each (seen[]). On a FILE that
# _scan_defs cannot read, set _list_fns's bad to "LINE<TAB>WHY" and fail.
#
# A sourced file is found by reading its argument, never by evaluating
# it: a literal path is taken as it is, and a path built from an
# expansion -- `source "${_SCRIPT_DIR}/toml.sh"`, every just-bashit
# library's idiom -- by its last component, beside FILE. That is where jbx
# co-fetches a just-bashit script's libraries, and where the idiom points.
# One it cannot find is named on stderr and skipped: listing it would mean
# running the expansion that names it.
_list_defs() {
	local file="${1}" out kind a b lib arg
	seen["${file}"]=1
	if ! out=$(_scan_defs "${file}"); then
		bad="${out##*E$'\t'}"
		return 1
	fi
	while IFS=$'\t' read -r kind a b; do
		case "${kind}" in
		F) names+=("${a}") ;;
		S)
			arg="${b//[\"\']/}"
			lib=""
			if [[ -n ${arg} && ${arg} != *[\$\`]* ]]; then
				lib="${arg}"
			elif [[ ${arg} == */* && ${arg##*/} != *[\$\`{}]* ]]; then
				lib="${file%/*}/${arg##*/}"
			fi
			if [[ -z ${lib} || ! -f ${lib} ]]; then
				echo "${_ME}: -l: not listing what line ${a} of ${file}" \
					"sources (${b:-a word spanning lines}): found only by" \
					"running the script" >&2
			elif [[ -z ${seen["${lib}"]:-} ]] && ! _list_defs "${lib}"; then
				echo "${_ME}: -l: not listing ${lib}, sourced at line ${a}" \
					"of ${file}: it cannot be read" >&2
			fi
			;;
		esac
	done <<<"${out}"
	return 0
}

# ---- execute ----------------------------------------------------------------

_run_python() {
	local script="${1}"
	shift

	if ! command -v uv >/dev/null 2>&1; then
		_log "uv not found — installing via just-bashit:pkg install-uv"
		# The one uv installer get-jb.sh and setup-system share: winget on
		# Windows, which picks the machine's native build even from an
		# emulated x64 shell, astral's install.sh elsewhere (#171). It
		# prints the directory uv is in, put first on PATH for this run.
		# -n reaches the nested run too, so nothing it fetches is cached.
		local nested=() uv_dir=""
		[[ ${OPT_NO_CACHE} -eq 1 ]] && nested=(-n)
		[[ ${OPT_NO_VERIFY} -eq 1 ]] && nested+=(--no-verify)
		# JB_NO_VERIFY carries --no-verify past the nested run to
		# install-uv's own fetch of astral's installer.
		if uv_dir="$(JB_NO_VERIFY="${OPT_NO_VERIFY}" \
			"${0}" "${nested[@]+"${nested[@]}"}" just-bashit:pkg install-uv)" &&
			[[ -n ${uv_dir} ]]; then
			PATH="${uv_dir}:${PATH}"
		fi
		hash -r 2>/dev/null || true
		command -v uv >/dev/null 2>&1 ||
			_err "uv install failed; try manually: jbx just-bashit:pkg install-uv"
	fi

	_log "using uv run"
	if [[ ${OPT_CLEAN} -eq 1 ]]; then
		local env_pairs=("HOME=${HOME}" "TERM=${TERM:-}" "PATH=${PATH}")
		local v
		for v in "${OPT_PASS[@]+"${OPT_PASS[@]}"}"; do
			env_pairs+=("${v}=${!v:-}")
		done
		env -i "${env_pairs[@]}" uv run "${script}" "$@"
	else
		uv run "${script}" "$@"
	fi
}

_run() {
	local script="${1}" func="${2:-}" lang="${3}"
	shift 3 || true

	if [[ ${lang} == "python" ]]; then
		[[ -n ${func} ]] &&
			_err "function mode not supported for Python; pass args directly"
		_run_python "${script}" "$@"
		return
	fi

	# One child sources the script, once, then calls FUNCTION, checking
	# between the two that the script defined it. A separate child that
	# sourced the script only to check ran its top level a second time
	# (just-bashit#141). declare -F, not a before/after diff, so a script
	# function that shadows a same-named environment function is accepted.
	# The check and the message use `builtin`: the script just sourced may
	# define a function named printf or declare. A missing function exits
	# 127, the shell's "command not found".
	local cmd q_script q_func q_miss
	printf -v q_script '%q' "${script}"
	cmd=". ${q_script}"
	if [[ -n ${func} ]]; then
		printf -v q_func '%q' "${func}"
		printf -v q_miss '%q' \
			"${_ME}: error: '${func}' is not a function defined by this script"
		local pre="" note="" q_note
		if [[ ${OPT_VERBOSE} -eq 1 ]]; then
			# In verbose mode, report when the script function shadows a
			# command, builtin or alias that existed before it was sourced.
			printf -v q_note '%q' \
				"${_ME}: note: script function '${func}' shadows a shell "
			pre="_jbx_pre=\$(type -t ${q_func} 2>/dev/null); "
			note="case \${_jbx_pre} in file | builtin | alias) builtin printf"
			note+=" '%s%s\n' ${q_note} \"\${_jbx_pre/file/command}\" >&2 ;;"
			note+=" esac; "
		fi
		cmd="${pre}${cmd} && { builtin declare -F ${q_func} >/dev/null ||"
		cmd+=" { builtin printf '%s\n' ${q_miss} >&2; exit 127; }; "
		cmd+="${note}${q_func} \"\$@\"; }"
	fi

	if [[ ${OPT_CLEAN} -eq 1 ]]; then
		local env_pairs=("HOME=${HOME}" "TERM=${TERM:-}" "PATH=${PATH}")
		local v
		for v in "${OPT_PASS[@]+"${OPT_PASS[@]}"}"; do
			env_pairs+=("${v}=${!v:-}")
		done
		env -i "${env_pairs[@]}" bash -c "${cmd}" -- "$@"
	else
		bash -c "${cmd}" -- "$@"
	fi
}

# ---- main -------------------------------------------------------------------

# -n fetches into a directory this shell owns, so it is THIS shell's EXIT
# trap that removes it, after the script has run -- not the trap of the
# $(...) subshell _acquire runs in. Made before _resolve, whose aliases.toml
# lookup fetches into it too (just-bashit#122).
if [[ ${OPT_NO_CACHE} -eq 1 ]]; then
	_NO_CACHE_DIR=$(mktemp -d "${TMPDIR:-/tmp}/just-runit.XXXXXX")
	trap 'rm -rf "${_NO_CACHE_DIR}"' EXIT
fi

URL=$(_resolve "${RAW_SPEC}")
_log "resolved: ${URL}"

SCRIPT=$(_acquire "${URL}")
_log "script: ${SCRIPT}"

[[ -n ${OPT_CHECKSUM} ]] && _verify "${SCRIPT}" "${OPT_CHECKSUM}"

# Before anything reads the script as code: -l below sources it.
if [[ ${OPT_FETCH} -eq 1 ]]; then
	echo "${SCRIPT}"
	exit 0
fi

SCRIPT_LANG=$(_detect_lang "${SCRIPT}" "${RAW_SPEC}")
_log "language: ${SCRIPT_LANG}"

if [[ ${OPT_LIST} -eq 1 ]]; then
	_list_fns "${SCRIPT}" "${SCRIPT_LANG}" "${RAW_SPEC}"
	exit 0
fi

_run "${SCRIPT}" "${FUNC}" "${SCRIPT_LANG}" "${ARGS[@]+"${ARGS[@]}"}"
