#!/usr/bin/env bash
# Run a command in the Hermes dev environment, whatever shell or cwd it is
# launched from: `scripts/run-in-hermes-env CMD [ARGS...]`.
#
# The environment is the one `activate` would give a shell, applied to this
# process only and then exec'd into CMD, so nothing leaks back and nothing has
# to be sourced or deactivated. It is synced first when there is none to
# inherit or the inherited one no longer matches its inputs
# (scripts/_activation.sh).
#
# Shebang for repo Python scripts, so `./scripts/foo.py` works from any cwd:
#     #!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
# The kernel appends the invoking script, and `bash -c` binds it to `$0`, so
# the shebang finds this file relative to the script and is independent of the
# cwd. `$BASH` for the second hop keeps it free of both the exec bit and a
# `PATH` lookup. The line must stay under 127 bytes, and `env -S` is GNU and
# newer-BSD; verify it if an older macOS or BSD is a target.
# macOS's stock bash 3.2 compares mtimes in whole seconds, so an input rewritten
# within the same second as its recorded stamp goes unnoticed there.
set -u

if [ "$#" -eq 0 ]; then
    printf 'usage: %s CMD [ARGS...]\n' "$0" >&2
    exit 2
fi

_here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/_activation.sh
. "$_here/_activation.sh"
hermes_ensure_env "$(dirname "$_here")" || exit 1

exec "$@"
