#!/usr/bin/env bash
# fs-schema-guard-bash-pre — PreToolUse Bash account-root snapshot.
#
# The Write/Edit/NotebookEdit path guard (fs-schema-guard.sh) does not see Bash:
# a folder created through mkdir/mv/cp/redirect bypasses it entirely. This hook
# is half of the Bash-channel net: it records the account root's immediate
# top-level entry names BEFORE the Bash command runs, so the PostToolUse twin
# (fs-schema-guard-bash-post.sh) can diff and flag only the strays THIS command
# newly created — never the pre-existing legacy backlog.
#
# The hook inspects account-root STATE, never the command string (command-string
# parsing was rejected as brittle and evadable). $PWD is the account dir.
#
# Fail open on every error (no session id, no python3, unlistable dir, unwritable
# tmp): a snapshot that cannot be taken must not block the command. exit 0 always
# — a PreToolUse snapshot never blocks; blocking is the post hook's job.

set -uo pipefail

# No stdin envelope (tty) — nothing to snapshot. Fail open.
[ -t 0 ] && exit 0
INPUT=$(cat)
[ -z "$INPUT" ] && exit 0

field() {
  printf '%s' "$INPUT" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(d.get('$1', '') or '')
except Exception:
    print('')
" 2>/dev/null || echo ""
}

TOOL_NAME=$(field tool_name)
[ "$TOOL_NAME" = "Bash" ] || exit 0

SESSION_ID=$(field session_id)
[ -z "$SESSION_ID" ] && exit 0

# Resolve the tmpdir the same way the manager's Node process does (libuv
# uv_os_tmpdir): TMPDIR, then TMP, then TEMP, then /tmp; strip a trailing slash.
# FS_GUARD_BASH_TMPDIR overrides for tests only — never set in production.
if [ -n "${FS_GUARD_BASH_TMPDIR:-}" ]; then
  TMP_DIR="$FS_GUARD_BASH_TMPDIR"
else
  TMP_DIR="${TMPDIR:-${TMP:-${TEMP:-/tmp}}}"
  TMP_DIR="${TMP_DIR%/}"
fi
SID_SAN=$(printf '%s' "$SESSION_ID" | sed 's/[^A-Za-z0-9_-]/_/g')
SNAP="$TMP_DIR/maxy-fsguard-snapshot-${SID_SAN}.txt"

# List the account root's immediate top-level entry names, one per line. python3
# os.listdir gives names only (no recursion). Any failure -> fail open.
ACCOUNT_DIR="$PWD" python3 -c '
import os, sys
acct = os.environ["ACCOUNT_DIR"]
try:
    names = os.listdir(acct)
except Exception:
    sys.exit(1)
sys.stdout.write("\n".join(names))
' > "$SNAP" 2>/dev/null || { rm -f "$SNAP" 2>/dev/null; exit 0; }

exit 0
