#!/bin/sh
# scripts/sandbox-bootstrap.sh — the Blaxel runner's process command (design-fleet, Wake call step 5; C-A2).
#
# Runs as root in the sandbox's `broker-<execution id>` process. Environment: CRTR_NODE_TOKEN, CRTR_RELEASE,
# CRTR_RELEASE_URL, CRTR_RELEASE_SHA256 and the rest the runner set. Once per sandbox it creates the `crtr` user
# (`crtrd` refuses root) and its directories; it installs the release if it is absent (download, sha256 check,
# unpack into a temp dir, rename into place, keep three), then hands over to `crtr-sandbox-start` as `crtr`.
# The node token reaches the start script on stdin, never in its environment, so it is in no process's
# /proc/<pid>/environ. It is not hidden from user `crtr` otherwise: the broker holds it in memory, and the agent's
# shell runs as the same user (design-fleet D13/D78 scope the token to this execution's node, nothing more). The final `exec` chain forks nothing (busybox `nsenter -S/-G` execs, and the token goes in as a here-document, not a pipe, which would
# put a forking shell in front of it), so the process Blaxel tracks as `broker-<execution id>` is the start script itself: stopping it reaches
# the node and the broker, and its exit means the broker is gone. A failed download or checksum exits non-zero and prints `crtr-sandbox-start: failed <reason>`
# as its last line (the runner's `status` reports that reason).
set -eu

fail() { echo "crtr-sandbox-start: failed $1${2:+ ($2)}" >&2; exit "${3:-1}"; }

: "${CRTR_RELEASE:?}" "${CRTR_RELEASE_URL:?}" "${CRTR_RELEASE_SHA256:?}" "${CRTR_NODE_TOKEN:?}"
case "$CRTR_RELEASE" in *[!A-Za-z0-9._-]*|'') fail bad_release "$CRTR_RELEASE" ;; esac

ROOT=${CRTR_SANDBOX_ROOT:-/opt/crtr}
RELEASES="$ROOT/releases"
RELEASE_DIR="$RELEASES/$CRTR_RELEASE"
RUN_USER=${CRTR_RUN_USER:-crtr}

if ! id "$RUN_USER" >/dev/null 2>&1; then
  adduser -D -h "/home/$RUN_USER" -s /bin/sh "$RUN_USER" || fail user_create
fi
mkdir -p /run/crtr /var/lib/crtr /work "$RELEASES"
chown "$RUN_USER" /run/crtr /var/lib/crtr /work
# pi's grep tool wants ripgrep; installing it once per sandbox avoids a GitHub download at the first grep.
if ! command -v rg >/dev/null 2>&1; then apk add --no-cache ripgrep >/dev/null 2>&1 || echo "crtr-sandbox-start: ripgrep not installed" >&2; fi

if [ ! -f "$RELEASE_DIR/.complete" ]; then
  tmp=$(mktemp -d "$RELEASES/.tmp.XXXXXX")
  trap 'rm -rf "$tmp"' EXIT
  wget -q -O "$tmp/runtime.tar.gz" "$CRTR_RELEASE_URL" || fail release_download "$CRTR_RELEASE"
  actual=$(sha256sum "$tmp/runtime.tar.gz" | cut -d' ' -f1)
  [ "$actual" = "$CRTR_RELEASE_SHA256" ] || fail release_checksum "expected $CRTR_RELEASE_SHA256, got $actual"
  mkdir "$tmp/unpack"
  tar -xzf "$tmp/runtime.tar.gz" -C "$tmp/unpack" || fail release_unpack
  : > "$tmp/unpack/.complete"
  # A concurrent start installing the same release wins the rename; both leave a complete directory.
  if ! mv "$tmp/unpack" "$RELEASE_DIR" 2>/dev/null; then [ -f "$RELEASE_DIR/.complete" ] || fail release_install; fi
  rm -rf "$tmp"
  trap - EXIT
fi
current_tmp="$ROOT/current.new.$$"
ln -sfn "$RELEASE_DIR" "$current_tmp" && mv -T "$current_tmp" "$ROOT/current"
# Keep the three newest releases (the current one among them).
ls -1t "$RELEASES" 2>/dev/null | grep -v '^\.' | tail -n +4 | while read -r old; do
  [ "$old" = "$CRTR_RELEASE" ] || rm -rf "${RELEASES:?}/$old"
done

token=$CRTR_NODE_TOKEN
unset CRTR_NODE_TOKEN
# busybox `su` forks, which leaves the tracked process a wrapper whose children outlive a stop; `nsenter` with no namespace flag only sets the
# uid and gid, then execs. It keeps the environment (as `su -p` did); the start script derives HOME and the layout itself.
exec nsenter -S "$(id -u "$RUN_USER")" -G "$(id -g "$RUN_USER")" node "$RELEASE_DIR/scripts/sandbox-start.mjs" <<EOT
$token
EOT
