#!/usr/bin/env bash
# rmm-search.sh — find machines in the GuruRMM fleet on the first try.
#
# Flexible, forgiving search: normalizes case/spaces/hyphens, matches across
# HOSTNAME + CLIENT + SITE + OS, and treats every query word as a required
# filter (AND). So a query naturally narrows and can't bleed across clients:
#   rmm-search.sh hyperv valleywide    -> only Valley Wide's hyperv host
#   rmm-search.sh hyperv               -> every hyperv box, each labeled by client
#   rmm-search.sh hyperv -c valleywide -> hard-scope to one client, then search
#
# Usage:
#   rmm-search.sh <words...> [-c|--client <name>] [--online] [--json] [-n N]
#   rmm-search.sh -c <client>            # list ALL machines for a client
#   rmm-search.sh --list-clients         # show distinct client names
#
# Online state is derived from last_seen recency (<5 min); the API is_connected
# flag is currently unreliable (null fleet-wide). Engine: rmm-search.py.
set -u
ROOT="${CLAUDETOOLS_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"

QUERY=""; CLIENT=""; ONLINE=0; JSON=0; LISTC=0; LIMIT=0
while [ $# -gt 0 ]; do
  case "$1" in
    -c|--client) CLIENT="${2:-}"; shift 2;;
    -n|--limit)  LIMIT="${2:-0}"; shift 2;;
    --online) ONLINE=1; shift;;
    --json) JSON=1; shift;;
    --list-clients) LISTC=1; shift;;
    -h|--help) sed -n '2,20p' "$0"; exit 0;;
    *) QUERY="${QUERY:+$QUERY }$1"; shift;;
  esac
done

if [ -z "$QUERY" ] && [ -z "$CLIENT" ] && [ "$LISTC" -eq 0 ]; then
  echo "[ERROR] give <words>, a --client, or --list-clients" >&2
  sed -n '12,17p' "$0" >&2; exit 1
fi

eval "$(bash "$ROOT/.claude/scripts/rmm-auth.sh" 2>/dev/null)" >/dev/null
if [ -z "${TOKEN:-}" ] || [ -z "${RMM:-}" ]; then
  echo "[ERROR] RMM auth failed (see rmm-auth.sh)" >&2
  bash "$ROOT/.claude/scripts/log-skill-error.sh" "rmm-search" "RMM auth failed via rmm-auth.sh (no TOKEN/RMM)" >/dev/null 2>&1
  exit 1
fi
AGENTS=$(curl -s "$RMM/api/agents" -H "Authorization: Bearer $TOKEN")
if [ -z "$AGENTS" ] || [ "${AGENTS:0:1}" != "[" ]; then
  echo "[ERROR] could not fetch agents: ${AGENTS:0:160}" >&2
  bash "$ROOT/.claude/scripts/log-skill-error.sh" "rmm-search" "GET /api/agents returned non-array/empty" --context "resp=${AGENTS:0:80}" >/dev/null 2>&1
  exit 1
fi

# Pipe agents on stdin (payload too large for argv on Windows); flags via env.
printf '%s' "$AGENTS" | QUERY="$QUERY" CLIENT="$CLIENT" ONLINE="$ONLINE" JSON="$JSON" LISTC="$LISTC" LIMIT="$LIMIT" \
  bash "$ROOT/.claude/scripts/py.sh" "$ROOT/.claude/scripts/rmm-search.py"
