#!/bin/sh
# Run rust's x.py inside the Alpine devfs sandbox (musl, 256-TLS loader, gcc),
# pointed at the mrustc-bootstrapped stage0. Hermetic: vendored deps, external LLVM.
# Usage: run-xpy.sh <SRCDIR> <PREFIXDIR> -- <x.py args...>
#   SRCDIR    : host path to the rust source tree (mounted at /src)
#   PREFIXDIR : host path for the install prefix   (mounted at /out)
set -eu
ROOT=/home/sergio/hammer
DEVFS=$ROOT/.dev-fs/alpine
MRUSTC=$ROOT/.scratch/mrustc
SRC=${1:?src dir required}; shift
PREFIX=${1:?prefix dir required}; shift
[ "${1:-}" = "--" ] && shift

# Optional read-only stage0 prefix (a prior hop's installed toolchain), bound at
# /stage0 when STAGE0 is set in the environment. bootstrap.toml's build.rustc can
# then reference /stage0/bin/rustc for a climb hop.
STAGE0_BIND=""
[ -n "${STAGE0:-}" ] && STAGE0_BIND="--ro-bind $STAGE0 /stage0"

exec bwrap \
  --bind "$DEVFS" / \
  --bind "$MRUSTC" /mrustc \
  --bind "$SRC" /src \
  --bind "$PREFIX" /out \
  $STAGE0_BIND \
  --dev /dev --proc /proc \
  --tmpfs /tmp --tmpfs /run \
  --setenv PATH /usr/bin:/bin:/usr/sbin:/sbin \
  --setenv HOME /root \
  --setenv TMPDIR /tmp \
  --setenv CC gcc --setenv CXX g++ \
  --setenv RUST_BACKTRACE 1 \
  --chdir /src \
  python3 x.py "$@"
