#!/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"
#   ORKESTR_DOCKER_MIRROR    0 = do not use the regional Docker Hub cache
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

# Regional Docker Hub cache. Every orkestr sandbox box runs a pull-through
# cache on the sandbox network gateway; when it answers, dockerd pulls Docker
# Hub images through it (fast after the first pull in the region, and no
# Docker Hub rate limits). Anything the cache cannot serve - it is down, or
# the image is private to your `docker login` - falls back to Docker Hub
# automatically. Opt out with ORKESTR_DOCKER_MIRROR=0.
MIRROR_ARGS=""
if [ "${ORKESTR_DOCKER_MIRROR:-1}" != "0" ]; then
  # Default gateway from /proc/net/route (no iproute2 needed), else the
  # egress proxy's host (restricted sandboxes).
  GW=$(awk 'function hx(s,  i, n) { n = 0; s = toupper(s)
                 for (i = 1; i <= length(s); i++) n = n * 16 + index("0123456789ABCDEF", substr(s, i, 1)) - 1
                 return n }
             $2 == "00000000" && $3 != "00000000" {
               h = $3; print hx(substr(h,7,2)) "." hx(substr(h,5,2)) "." hx(substr(h,3,2)) "." hx(substr(h,1,2)); exit }' \
       /proc/net/route 2>/dev/null || true)
  if [ -z "$GW" ] && [ -n "${HTTP_PROXY:-}" ]; then
    GW=$(echo "$HTTP_PROXY" | sed -E 's#^[a-z]+://##; s#[:/].*$##')
  fi
  if [ -n "$GW" ] && curl -fsS -m 2 --noproxy '*' -o /dev/null "http://$GW:5000/v2/" 2>/dev/null; then
    MIRROR_ARGS="--registry-mirror=http://$GW:5000 --insecure-registry=$GW:5000"
    export NO_PROXY="$GW${NO_PROXY:+,$NO_PROXY}" no_proxy="$GW${no_proxy:+,$no_proxy}"
    echo "orkestr-docker-boot: Docker Hub pulls go through the regional cache at $GW:5000"
  fi
fi

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