#!/bin/bash
# Claude Code Patcher — standalone installer for v2.1.47
# Usage: sudo bash install.sh [--all] [--skip-cli]
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CLI_JS="$SCRIPT_DIR/cli.js"
PATCHER="$SCRIPT_DIR/claude_code_patcher.py"
CONFIG="$SCRIPT_DIR/patcher.config.json"

TARGET="/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js"
[ ! -f "$TARGET" ] && TARGET="/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js"
[ ! -f "$TARGET" ] && TARGET="/opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js"

if [ ! -f "$TARGET" ]; then
  echo "ERROR: Claude Code cli.js not found. Install Claude Code first."
  exit 1
fi

# Install patched cli.js
if [ "$1" != "--skip-cli" ]; then
  echo "Installing patched cli.js..."
  BACKUP="$TARGET.bak.$(date +%Y%m%d%H%M%S)"
  cp "$TARGET" "$BACKUP"
  cp "$CLI_JS" "$TARGET"
  node --check "$TARGET" || { cp "$BACKUP" "$TARGET"; echo "SYNTAX ERROR, rolled back"; exit 1; }
  echo "Installed. Backup: $BACKUP"
fi

# Apply user settings
if [ -f "$PATCHER" ] && [ -f "$CONFIG" ]; then
  echo "Applying user settings..."
  python3 "$PATCHER" --config "$CONFIG" --all --skip-cli-patch --skip-update
fi

echo "Done. Run 'claude --version' to verify."
