#!/bin/bash
# PreToolUse(Bash) — whitelist tmux subcommands only.
# Exit 0 = allow, exit 2 = block.
set -u

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

# Must start with an allowed tmux subcommand or cat /tmp/claude/
ALLOWED_PATTERN='^tmux (list-panes|capture-pane|display-message|send-keys|list-sessions|list-windows)( |$)'
CAT_PATTERN='^cat /tmp/claude/'

# Build / git / gh commands explicitly allowed for landing PRs from the
# orchestrator pane. Shell operators (|, &&, ;, backticks, $()) are blocked
# on ALL allowed branches — chained commands must be run as separate Bash
# tool calls so each invocation is independently validated.
DEV_PATTERN='^(pnpm|bunx?|node|npx|git|gh|scripts/committer|bash scripts/committer|bash \./scripts/committer|\./scripts/committer|ls|cat|grep|find|head|tail|wc|jq|which|pwd|date|echo|ssh|scp|tailscale|sshpass|ps|hostname|uname|sudo|apt-get|apt) '

# Single operator-block check applied to every allowed branch below.
# Blocks: ; | & backtick $( ) > < and newlines. Chained or redirected
# commands must be run as separate Bash tool calls.
has_shell_operators() {
  if echo "$COMMAND" | grep -qE '[;|&`<>]|\$\('; then
    return 0
  fi
  # Detect embedded newlines (process substitution / heredoc style). Using
  # `case` against $'\n' avoids the grep-empty-pattern matching foot-gun.
  case "$COMMAND" in
    *$'\n'*) return 0 ;;
  esac
  return 1
}

if echo "$COMMAND" | grep -qE "$ALLOWED_PATTERN"; then
  if has_shell_operators; then
    echo "Blocked: shell operators not allowed in tmux commands. Use a single tmux command." >&2
    exit 2
  fi
  exit 0
fi

if echo "$COMMAND" | grep -qE "$CAT_PATTERN"; then
  if has_shell_operators; then
    echo "Blocked: shell operators not allowed. Use a single command." >&2
    exit 2
  fi
  exit 0
fi

if echo "$COMMAND" | grep -qE "$DEV_PATTERN"; then
  if has_shell_operators; then
    echo "Blocked: shell operators (|, &&, ;, backticks, \$(), <, >, newlines) not allowed in build/git/gh commands. Run each step as a separate Bash tool call." >&2
    exit 2
  fi
  exit 0
fi

echo "Blocked: only tmux inspection, agent event commands, and build/git/gh commands allowed. Spawn an Agent for other work." >&2
exit 2
