#!/usr/bin/env bash
# tool-confine-install.sh — append the tool-shell confinement to Claude Code shell
# snapshots. Run from the SessionStart hook, and safe to run by hand at any time.
#
# Every Bash tool call sources its session's snapshot; a session that already exists
# picks the confinement up on its next tool call without being restarted.
#
# Silent and fail-open: a snapshot that cannot be patched simply stays unconfined.
set -uo pipefail

CLAUDE_HOME="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
SNAP_DIR="$CLAUDE_HOME/shell-snapshots"
MARKER='# overdeck:tool-confine'
LINE=". \"\$HOME/.claude/lib/tool-confine.sh\" 2>/dev/null || true  $MARKER"

[[ -d "$SNAP_DIR" ]] || exit 0
[[ -r "$HOME/.claude/lib/tool-confine.sh" ]] || exit 0

patched=0
for f in "$SNAP_DIR"/*.sh; do
  [[ -f "$f" && -w "$f" ]] || continue
  content=$(<"$f") || continue
  [[ "$content" == *"$MARKER"* ]] && continue
  # A snapshot the harness is appending to right now must not be patched mid-write.
  # Recent harness versions end the file with its PATH export; older ones end elsewhere,
  # so a file untouched for a few seconds counts as finished regardless of its last line.
  if [[ "${content##*$'\n'}" != export\ PATH=* ]]; then
    mtime=$(stat -c %Y "$f" 2>/dev/null) || continue
    (( ${EPOCHSECONDS:-$(date +%s)} - mtime >= 5 )) || continue
  fi
  printf '%s\n' "$LINE" >> "$f" && patched=$(( patched + 1 ))
done

[[ "${1:-}" == --verbose ]] && printf 'tool-confine: patched %d snapshot(s)\n' "$patched"
exit 0
