#!/bin/sh
# orkestr-docker-boot - start Docker inside an orkestr sandbox.
#
# Served at https://orkestr.eu/scripts/sandbox-docker-boot.sh and fetched by
# the template recipe on /docs/sandboxes/docker. Customer templates capture
# whatever this file says at their build time, so keep it backward compatible.
#
# Runs as the template's start_command (once, detached, on first boot). The
# sandbox root is an overlay, and Docker's overlayfs snapshotter cannot stack
# an overlay on an overlay, so Docker's data-root must live on ext4:
#
#   - a volume is attached (/persist): data-root on the volume itself. Disk
#     backed, survives terminate, no RAM cost. Recommended for real builds.
#   - no volume: a sparse ext4 image on tmpfs. Only the blocks Docker writes
#     use memory, so size the sandbox for your images (medium or larger).
#
# Env (set at create time):
#   ORKESTR_DOCKER_DISK_MB   size cap of the in-memory image (default: tmpfs free - 256 MB)
#   ORKESTR_DOCKER_ARGS      extra dockerd flags, e.g. "--firewall-backend=nftables"
set -eu

DATA=/var/lib/docker
mkdir -p "$DATA"

if mountpoint -q "$DATA"; then
  : # already prepared (re-run)
elif mountpoint -q /persist; then
  mkdir -p /persist/docker
  mount --bind /persist/docker "$DATA"
  echo "orkestr-docker-boot: data-root on volume /persist/docker"
else
  IMG=/tmp/orkestr-docker.ext4
  if [ -z "${ORKESTR_DOCKER_DISK_MB:-}" ]; then
    free_mb=$(df -Pm /tmp | awk 'NR==2 {print $4}')
    ORKESTR_DOCKER_DISK_MB=$((free_mb - 256))
  fi
  [ "$ORKESTR_DOCKER_DISK_MB" -ge 512 ] || {
    echo "orkestr-docker-boot: only ${ORKESTR_DOCKER_DISK_MB} MB for Docker - use a bigger sandbox or attach a volume" >&2
    exit 1
  }
  truncate -s "${ORKESTR_DOCKER_DISK_MB}M" "$IMG"
  mkfs.ext4 -q -F -E lazy_itable_init=1,lazy_journal_init=1 -m 0 "$IMG"
  mount -o loop "$IMG" "$DATA"
  echo "orkestr-docker-boot: data-root on ${ORKESTR_DOCKER_DISK_MB} MB in-memory ext4 (attach a volume for disk-backed storage)"
fi

# shellcheck disable=SC2086
exec dockerd ${ORKESTR_DOCKER_ARGS:-}
