#!/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 unless `$ROOT/releases/<release>` already holds
# it (complete, and unpacked from the tarball whose sha256 the wake names, recorded in its `.sha256`): that is the
# fast path, taken in a sandbox made from the release image (release-image.ts), which carries the release, `crtr`,
# `rg` and the directories, so nothing is installed or downloaded. Otherwise (the stock image, a release the image
# lacks, an image built from another tarball) it downloads, checks the sha256, unpacks into a temp dir and renames
# into place (replacing a release of the same name that fails the check), keeps three; then hands over to
# `crtr-sandbox-start` as `crtr`. Each phase prints `crtr-boot: <phase> up=<seconds>` (the VM's uptime, which the
# start script reads too, so it can report every phase of the boot together).
# 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

# /proc/uptime is read with a builtin: no fork. Empty when unreadable, which the start script reports as unknown.
uptime_now() { up=; read -r up _ < /proc/uptime 2>/dev/null || up=; }
phase() { uptime_now; echo "crtr-boot: $1 up=${up:-unknown}${2:+ $2}" >&2; }
uptime_now
CRTR_BOOT_START_UP=$up
phase bootstrap_start

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
[ ! -d "/home/$RUN_USER" ] || chown "$RUN_USER" "/home/$RUN_USER"
# pi's grep tool wants ripgrep; the release image has it, and installing it once per sandbox avoids a GitHub download at the first grep.
rg=present
if ! command -v rg >/dev/null 2>&1; then
  if apk add --no-cache ripgrep >/dev/null 2>&1; then rg=installed; else rg=missing; echo "crtr-sandbox-start: ripgrep not installed" >&2; fi
fi

# The release is trusted only when it is complete and was unpacked from the tarball this wake names. A directory of the right name without that
# record (an install by an older bootstrap, an image built from another tarball of the same version) is replaced, never run unchecked.
release_current() { [ -f "$RELEASE_DIR/.complete" ] && [ "$(cat "$RELEASE_DIR/.sha256" 2>/dev/null)" = "$CRTR_RELEASE_SHA256" ]; }

if release_current; then
  source=present
else
  source=downloaded
  [ ! -e "$RELEASE_DIR" ] || source=replaced
  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
  printf '%s\n' "$actual" > "$tmp/unpack/.sha256"
  : > "$tmp/unpack/.complete"
  # A directory that fails the check is moved aside (removed with $tmp); one a concurrent start just installed from the same tarball is left, and wins.
  if [ -e "$RELEASE_DIR" ] && ! release_current; then mv "$RELEASE_DIR" "$tmp/stale" 2>/dev/null || true; fi
  if ! mv "$tmp/unpack" "$RELEASE_DIR" 2>/dev/null; then release_current || fail release_install; fi
  rm -rf "$tmp"
  trap - EXIT
fi
phase release_ready "source=$source rg=$rg"
uptime_now
export CRTR_BOOT_START_UP CRTR_BOOT_RELEASE_UP=$up CRTR_BOOT_RELEASE_SOURCE=$source CRTR_BOOT_RG=$rg
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
