class Discharger::SetupRunner::Commands::PgToolsCommand

def generic_wrapper_content(tool)

def generic_wrapper_content(tool)
  <<~BASH
    #!/usr/bin/env bash
    set -e
    CONTAINER="#{container_name}"
    # Docker first: use container's #{tool} if running
    if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${CONTAINER}$"; then
      echo "Using #{tool} from Docker container: $CONTAINER" >&2
      # Parse arguments to handle --file option specially
      # When running in Docker, host paths don't exist in the container
      # so we pipe file content via stdin instead
      INPUT_FILE=""
      HAS_USER=""
      ARGS=()
      while [[ $# -gt 0 ]]; do
        case $1 in
          --file)
            INPUT_FILE="$2"
            shift 2
            ;;
          --file=*)
            INPUT_FILE="${1#*=}"
            shift
            ;;
          -f)
            INPUT_FILE="$2"
            shift 2
            ;;
          -U|--username|--username=*)
            HAS_USER="1"
            ARGS+=("$1")
            shift
            ;;
          *)
            ARGS+=("$1")
            shift
            ;;
        esac
      done
      # Default to postgres user if not specified (container runs as root)
      if [[ -z "$HAS_USER" ]]; then
        ARGS=("-U" "postgres" "${ARGS[@]}")
      fi
      if [[ -n "$INPUT_FILE" ]]; then
        docker exec -i "$CONTAINER" #{tool} "${ARGS[@]}" < "$INPUT_FILE"
      else
        exec docker exec -i "$CONTAINER" #{tool} "${ARGS[@]}"
      fi
      exit 0
    fi
    # Fallback to system #{tool} (skip this wrapper in PATH to avoid infinite loop)
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    CLEAN_PATH="${PATH//$SCRIPT_DIR:/}"
    CLEAN_PATH="${CLEAN_PATH%:$SCRIPT_DIR}"
    FALLBACK=$(PATH="$CLEAN_PATH" command -v #{tool} 2>/dev/null)
    if [[ -n "$FALLBACK" ]]; then
      exec "$FALLBACK" "$@"
    fi
    echo "Error: #{tool} not found. Start Docker or install PostgreSQL client tools." >&2
    exit 1
  BASH
end