#!/bin/bash
# amico-opencode-fleet-guard — fleet guard for the Amicode extension.
# Reads fleet role from ~/.amico/ops/fleet/fleet.json. On a machine whose role
# is "client", exit 1 immediately: the extension's health probe then rides the
# SSH tunnel to the canonical server, or fails closed if the tunnel is down —
# a client must NEVER spawn a local fork. (harmoniqs/amicode#279, #324, #338)
#
# Fleet config: ~/.amico/ops/fleet/fleet.json
#   { "role": "standalone"|"server"|"client", "canonical": { "host": "...", "port": 4096, "sshAlias": "..." } }
#   No file = standalone (safe default — spawns locally like pre-fleet Amicode).
#
# Install to ~/.local/bin on every host and point amicode.opencodeBinary at it:
#   cp tools/fleet/amico-opencode-fleet-guard ~/.local/bin/amico-opencode-fleet-guard
#   # then in settings.json (scope: machine): "amicode.opencodeBinary": "$HOME/.local/bin/amico-opencode-fleet-guard"
#
# Go Standalone (CONTEXT.md): sets role to "standalone" in fleet.json (or deletes
# it). The guard then allows a local spawn — no tunnel required.

FLEET_CONFIG="$HOME/.amico/ops/fleet/fleet.json"

# Determine role from fleet.json. No file or parse failure = standalone.
ROLE="standalone"
if [ -f "$FLEET_CONFIG" ]; then
  # Extract role with lightweight JSON parsing (no jq dependency)
  PARSED_ROLE="$(grep -o '"role"[[:space:]]*:[[:space:]]*"[^"]*"' "$FLEET_CONFIG" 2>/dev/null | head -1 | sed 's/.*"role"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')"
  if [ -n "$PARSED_ROLE" ]; then
    ROLE="$PARSED_ROLE"
  fi
fi

# Client role: refuse to spawn — panel must ride the tunnel.
if [ "$ROLE" = "client" ]; then
  echo "[amico-fleet-guard] refusing to spawn a local opencode server on a fleet client — panel will ride the tunnel" >&2
  echo "[amico-fleet-guard] hint: canonical offline? Run 'Amicode: Fleet — Go Standalone' to work locally." >&2
  exit 1
fi

# Standalone or server: resolve opencode binary — frozen first, then VSIX, then dev checkout.
FROZEN="$HOME/.amico/server/bin/opencode"
VSIX_BIN="$(ls -dt "$HOME"/.vscode/extensions/harmoniqs.amicode-*/vendor/opencode/darwin-arm64/opencode 2>/dev/null | head -1)"
DEV_BIN="$(ls -dt "$HOME"/harmoniqs/amicode/packages/extension/vendor/opencode/darwin-arm64/opencode "$HOME"/armonia/repos/amicode/packages/extension/vendor/opencode/darwin-arm64/opencode 2>/dev/null | head -1)"
if [ -x "$FROZEN" ]; then
  exec "$FROZEN" "$@"
elif [ -n "$VSIX_BIN" ] && [ -x "$VSIX_BIN" ]; then
  exec "$VSIX_BIN" "$@"
elif [ -n "$DEV_BIN" ] && [ -x "$DEV_BIN" ]; then
  exec "$DEV_BIN" "$@"
else
  echo "[amico-fleet-guard] no opencode binary found (frozen, VSIX, or dev checkout)" >&2
  exit 1
fi
