#!/bin/bash
# openzoo, all of it, on this Omarchy machine — pulled from git. Re-running
# RIPS OUT every previous openzoo install first (your memory is kept), then
# installs the current three fresh:
#
#   curl -fsSL openzoo.fun/omarchymax | bash
#
#   1. the agent   openzoo in Omarchy's agent list: Claude Code paid per call, no key
#   2. the bar     the openzoo bar widget: ask any model, recall your bound corpus
#   3. ingest      the openzoo-ingest plugin: clipboard, notifications, screenshots,
#                  agent transcripts, shell history → your own local leCore memory,
#                  every 10 minutes. Replaces any earlier curl-installed copy.
#
# Each step is its own installer and its own repo; a failure in one does not
# stop the others. Nothing here sends data off the machine: ingest is local
# until you configure a shared brain yourself.
set -u
ok=(); failed=()
step() {
  local name="$1"; shift
  echo; echo "━━━ $name"
  if "$@"; then ok+=("$name"); else failed+=("$name"); echo "!!! $name failed — continuing"; fi
}

# One CLI, one :8402, one wallet. A re-curl is the update path.
# Two proxies were our fault: bar spend and the agent CLI each showed
# a different $ because each held its own burner. Kill extras, pin latest.
oz_self_heal() {
  echo "==> openzoo self-heal (one CLI, one proxy, one wallet)"
  mkdir -p "$HOME/.openzoo"
  if command -v npx >/dev/null 2>&1; then
    npx --yes -p openzoo@latest true \
      && echo "    openzoo $(npm view openzoo version 2>/dev/null || echo latest)" \
      || echo "    WARN: could not prefetch openzoo@latest"
  else
    echo "    WARN: npx missing — install Node so the agent can self-update"
  fi
  if command -v lsof >/dev/null 2>&1; then
    pids=$(lsof -t -iTCP:8402 -sTCP:LISTEN 2>/dev/null || true)
    if [ -n "$pids" ]; then
      echo "    stopping stale proxy on :8402"
      # shellcheck disable=SC2086
      kill $pids 2>/dev/null || true
      sleep 0.3
      kill -9 $pids 2>/dev/null || true
    fi
  fi
  pkill -f '/node_modules/openzoo/bin/openzoo.js' 2>/dev/null || true
  pkill -f 'openzoo.js proxy' 2>/dev/null || true
  WALLET="$HOME/.openzoo/wallet.json"
  if [ -f "$WALLET" ]; then
    addr=$(python3 - <<'PY' 2>/dev/null || true
import json, os
p = os.path.expanduser("~/.openzoo/wallet.json")
d = json.load(open(p))
sk = d if isinstance(d, list) else d.get("solana")
pub = bytes(sk[32:64])
A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
n = int.from_bytes(pub, "big")
s = ""
while n:
    n, r = divmod(n, 58)
    s = A[r] + s
pad = 0
for b in pub:
    if b == 0: pad += 1
    else: break
print(("1" * pad) + s)
PY
)
    echo "    wallet $WALLET${addr:+  $addr}"
  else
    echo "    no wallet yet — next \`openzoo claude\` mints one at $WALLET"
  fi
  echo "    bar + agent share this wallet and :8402. do not start a second proxy."
}

oz_self_heal

# RIP OUT THE OLD FIRST. This is a reinstall, not a merge: every earlier shape
# of these three things is removed before the current one goes in, so a box
# never carries two generations at once. Your MEMORY is kept —
# ~/.local/share/openzoo-ingest/lecore-memory is never touched here.
step "0/3 remove previous openzoo installs (memory kept)" bash -c '
  for id in openzoo openzoo-ingest; do
    [ -d "$HOME/.config/omarchy/plugins/$id" ] && omarchy plugin remove "$id" --yes || true
  done
  systemctl --user disable --now openzoo-ingest.timer openzoo-lecore.service 2>/dev/null || true
  rm -f "$HOME/.config/systemd/user/openzoo-ingest.service" "$HOME/.config/systemd/user/openzoo-ingest.timer" "$HOME/.config/systemd/user/openzoo-lecore.service"
  systemctl --user daemon-reload 2>/dev/null || true
  S="$HOME/.local/share/openzoo-ingest/src"
  [ -L "$S" ] && rm -f "$S"
  [ -d "$S" ] && rm -rf "$S"
  rm -rf "$HOME"/.local/share/openzoo-ingest/src.pre-plugin.* 2>/dev/null
  rm -f "$HOME/.local/bin/openzoo-ingest"
  # the old bar placement and hotkey are re-applied by /bar; drop the stale entry so it cannot double up
  python3 - <<PY 2>/dev/null || true
import json,os
p=os.path.expanduser("~/.config/omarchy/shell.json")
try: d=json.load(open(p))
except Exception: raise SystemExit
lay=d.get("bar",{}).get("layout",{})
for s in lay: lay[s]=[i for i in lay[s] if (i.get("id") if isinstance(i,dict) else i)!="openzoo"]
d["plugins"]=[x for x in d.get("plugins",[]) if (x.get("id") if isinstance(x,dict) else x) not in ("openzoo","openzoo-ingest")]
json.dump(d,open(p,"w"),indent=1)
PY
  echo "previous installs removed"'

step "1/3 agent  (openzoo.fun/omarchy)" bash -c 'curl -fsSL https://openzoo.fun/omarchy | bash'
step "2/3 bar    (openzoo.fun/bar)"     bash -c 'curl -fsSL https://openzoo.fun/bar | bash'
# Ingest is an Omarchy PLUGIN now (service kind: draws nothing, keeps the
# loopback memory daemon and the ten-minute bind timer enabled). The plugin
# manager owns the checkout; install.sh --plugin links it into place and
# REPLACES whatever an earlier curl-style install left behind (the old
# checkout is kept as ~/.local/share/openzoo-ingest/src.pre-plugin.*).
step "3/3 ingest (omarchy plugin: staccDOTsol/openzoo-ingest)" bash -c '
  P="$HOME/.config/omarchy/plugins/openzoo-ingest"
  if [ -d "$P/.git" ]; then
    omarchy plugin update openzoo-ingest --yes
  else
    omarchy plugin add https://github.com/staccDOTsol/openzoo-ingest.git --enable --yes
  fi
  bash "$P/install.sh" --plugin "$P"'

echo
echo "━━━ done"
[ ${#ok[@]} -gt 0 ]     && printf '  ok:      %s\n' "${ok[@]}"
[ ${#failed[@]} -gt 0 ] && printf '  FAILED:  %s\n' "${failed[@]}"
echo
echo "  Super+Shift+Z                          the bar (ask / recall)"
echo "  openzoo-ingest watch                   the live ingest bar"
echo "  openzoo-ingest status                  what has been bound"
echo

# END BY STARTING THE AGENT. An install that finishes on a summary and a
# prompt makes the person go find the menu; this one sets openzoo as the
# default agent and hands this terminal to it. `--install` is the same path
# Setup > Default > Agent takes: mise pulls the package, the default is
# written, and Claude Code (paid per call, no key) starts inline.
OM="${OMARCHY_PATH:-/usr/share/omarchy}"; [ -d "$OM" ] || OM="$HOME/.local/share/omarchy"
if [ -t 1 ] && grep -q openzoo "$OM/bin/omarchy-default-agent" 2>/dev/null; then
  echo "━━━ starting the agent (openzoo is now the default: Setup > Default > Agent)"
  exec "$OM/bin/omarchy-default-agent" --install openzoo
fi
echo "  omarchy agent                          start it (openzoo: Setup > Default > Agent)"
[ ${#failed[@]} -eq 0 ]
