#!/bin/bash
# Omnigent claude shim (v1, cswap-supported session mode): route each session to a
# load-balanced cswap account via `cswap run <acct> --share-history`. Account-keyed profile
# dirs mean multiple sessions on one account SHARE the dir + Claude's refresh lock, so their
# token refreshes coordinate (no mutual logout). projects/ symlinked to ~/.claude so Omnigent
# cold-resume works. Cross-machine isolation via the pool allowlist (~/.omni-cswap/pool).
set -uo pipefail
SELF="$(cd "$(dirname "$0")" && pwd)"
export PATH="$(printf '%s' "$PATH" | tr ':' '\n' | grep -vxF "$SELF" | paste -sd: -)"
CSWAP_PY="$(dirname "$(readlink -f "$(command -v cswap 2>/dev/null)" 2>/dev/null)" 2>/dev/null)/python"; [ -x "$CSWAP_PY" ] || CSWAP_PY=python3

# Utility invocations are not sessions — pass straight to real claude (default login).
case "${1:-}" in
  auth|config|setup-token|mcp|doctor|update|install|migrate-installer|models|--version|-v|--help|-h)
    exec claude "$@" ;;
esac

ACCT="$(python3 "$SELF/pick_account.py" 2>>"$SELF/shim.log")"
if [ -n "${OMNI_CSWAP_DRYRUN:-}" ]; then echo "DRYRUN acct=${ACCT:-<none>} realclaude=$(command -v claude)"; exit 0; fi
if [ -z "$ACCT" ]; then echo "$(date -u +%FT%TZ) no pool account -> default login" >>"$SELF/shim.log"; exec claude "$@"; fi
# Pre-accept the per-folder trust dialog in the account's config dir (each cswap account has its
# own, so a folder trusted under one account still prompts under another). Best-effort.
"$CSWAP_PY" "$SELF/pretrust.py" "$ACCT" "$PWD" 2>>"$SELF/shim.log" || true
# Host-level default permission mode: if this host opted in (`touch ~/.omni-cswap/bypass`) and the
# session didn't already choose a mode, run autonomous (bypassPermissions). Use on headless hosts
# (e.g. backstage); leave the marker absent on interactive machines to keep approval prompts.
if [ -f "$SELF/bypass" ]; then
  case " $* " in *" --permission-mode "*) : ;; *) set -- "$@" --permission-mode bypassPermissions ;; esac
fi
echo "$(date -u +%FT%TZ) session=${OMNIGENT_SESSION_ID:-?} -> account $ACCT" >>"$SELF/shim.log"
exec cswap run "$ACCT" --share-history -- "$@"
