#!/usr/bin/env bash
# llm-swarm client one-line install for Linux (GH #50).
#
#   curl -fsSL https://latest.llm-swarm.com/install.sh | bash
#
# Copies swarm_client/ + harness registration into ~/.local/share/swarm-client,
# adds a `swarm` launcher to ~/.local/bin, registers local models into
# popular harnesses (idempotent, backup+restore). Uninstall: --uninstall.
set -euo pipefail

DEST="$HOME/.local/share/swarm-client"
BIN_DIR="$HOME/.local/bin"
RAW_BASE="${SWARM_INSTALL_BASE:-https://latest.llm-swarm.com/download}"

if [[ "${1:-}" == "--uninstall" ]]; then
  rm -rf "$DEST"
  rm -f "$BIN_DIR/swarm"
  echo "swarm client removed."
  exit 0
fi

mkdir -p "$DEST" "$BIN_DIR"
fetch() { # fetch <repo-rel-path> <dest>
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$RAW_BASE/$1" -o "$2";
  else wget -qO "$2" "$RAW_BASE/$1"; fi
}

echo "==> downloading swarm client…"
fetch "swarm-client.tar.gz" "$DEST/swarm-client.tar.gz"
tar -xzf "$DEST/swarm-client.tar.gz" -C "$DEST"
rm -f "$DEST/swarm-client.tar.gz"

cat > "$BIN_DIR/swarm" <<EOF
#!/usr/bin/env bash
exec python3 "$DEST/swarm_client/app.py" "\$@"
EOF
chmod +x "$BIN_DIR/swarm"

echo "==> registering local models into harnesses (idempotent; backups written as *.pre-swarm-*)"
python3 "$DEST/scripts/register_harnesses.py" \
  --endpoint "${SWARM_ENDPOINT:-http://127.0.0.1:8600/v1}" \
  --models "${SWARM_MODELS:-}" || echo "harness registration failed (recoverable; run manually)" >&2

echo "==> done. Run: swarm   (ensure $BIN_DIR is on PATH)"
