#!/bin/sh
# bostrat node boot: first-boot volume layout, then hand off to the CLI.
# Everything under $HOME sits on the Fly volume (see node.Dockerfile).
set -e
mkdir -p "$HOME/repos"
# Boxes commit as they work; give git an identity on first boot only — the
# operator can overwrite it (it persists in $HOME/.gitconfig on the volume).
git config --global user.name >/dev/null 2>&1 || git config --global user.name "bostrat node"
git config --global user.email >/dev/null 2>&1 || git config --global user.email "node@bostrat.ai"
# The agent drives boxes on a host tmux server (the Pi's globo-tmux.service
# equivalent): keep one alive with a detached keeper session.
SOCKET="${BOSTRAT_TMUX_SOCKET:-/tmp/tmux-0/default}"
mkdir -p "$(dirname "$SOCKET")"
tmux -S "$SOCKET" has-session 2>/dev/null || tmux -S "$SOCKET" new-session -d -s keeper "sleep infinity"
# The server is a daemon beside the agent, not its child: when `bostrat-node
# run` relaunches a stalled agent (BP-NG-R2 — heartbeat.json stale 3 min →
# SIGTERM/SIGKILL → respawn, node-cli.js createRunSupervisor), every box keeps
# running here and the lead resumes by session id on the next drive.
# In-VM OOM guard (BP-NG-R4 / D4): earlyoom is in the image (node.Dockerfile)
# and `bostrat-node run` starts and relaunches it — agent/src/oom-guard.js, the
# same code that guards a resident node (BP-NG-I10). Nothing to start here.
# Global-install layout (the GHCR image / npm -g) has bostrat-node on PATH;
# staged repo-context builds (`bostrat-node fly` wizard) run the tree copy.
# Both exec `run` — the foreground SUPERVISOR (self-update restarts + the stall
# watchdog), so this script needs no loop of its own; if the supervisor itself
# dies the machine's restart policy (always) brings the whole node back.
if command -v bostrat-node >/dev/null 2>&1; then
  exec bostrat-node run
else
  exec node /app/agent/bin/bostrat-node.js run
fi
