#!/bin/sh
# Path A: rebuild the mrustc stage0 rustc+cargo with a MUSL host triple, so
# CFG_COMPILER_HOST_TRIPLE=x86_64-unknown-linux-musl is baked in. This lets
# run_rustc's cargo build proc-macros/build-scripts natively (host==target==musl)
# without the proxy --target hack. LLVM + mrustc are reused (already built).
# Output lands in output-1.90.0-x86_64-unknown-linux-musl/.
set -eu
ROOT=/home/sergio/hammer
DEVFS=$ROOT/.dev-fs/alpine
MRUSTC=$ROOT/.scratch/mrustc
T=x86_64-unknown-linux-musl

run() {
  bwrap \
    --bind "$DEVFS" / \
    --bind "$MRUSTC" /mrustc \
    --dev /dev --proc /proc \
    --tmpfs /tmp --tmpfs /run \
    --setenv PATH /usr/bin:/bin:/usr/sbin:/sbin \
    --setenv HOME /root --setenv TMPDIR /tmp \
    --setenv MRUSTC_TARGET_VER 1.90 \
    --setenv CC gcc --setenv CXX g++ \
    --chdir /mrustc \
    make -f minicargo.mk \
      RUSTC_VERSION=1.90.0 \
      MRUSTC_TARGET=$T RUSTC_TARGET=$T \
      RUSTC_INSTALL_BINDIR=bin PARLEVEL=8 \
      "$@"
}

# minicargo OUT_DIR host/target split fix.
# With RUSTC_TARGET set (even when host==target==musl) minicargo runs each cargo
# build-script under cargo-build/host/build_X/, but the *target* crate's
# include!/include_bytes!(concat!(env!("OUT_DIR"),"/..")) resolves OUT_DIR to
# cargo-build/build_X/ (no host/, empty) -> mrustc aborts with signal 6. Bit us on
# libsqlite3-sys (bindgen.rs) and the cargo binary (man.tgz). host==target so the
# script outputs are bit-identical; symlink target dir -> host dir. Late sys-crates
# (cargo, curl, openssl, libgit2-sys, libssh2-sys) only run their scripts near the
# end, so this is (re)applied between incremental cargo-build retries below.
symlink_outdirs() {
  cb="$MRUSTC/output-1.90.0-$T/cargo-build"
  [ -d "$cb/host" ] || return 0
  for d in "$cb"/host/build_*/; do
    [ -d "$d" ] || continue
    b=$(basename "$d")
    [ -e "$cb/$b" ] && continue           # symlink or real dir already present
    ln -s "host/$b" "$cb/$b"
  done
}

echo "=== [1/3] LIBS (musl bootstrap std) ==="
run LIBS
echo "=== [2/3] rustc (musl host) ==="
run output-1.90.0-$T/rustc
echo "=== [3/3] cargo (musl host) ==="
# Retry loop: minicargo is incremental, so each retry only redoes the crate that
# failed onward. `until` keeps the failing build out of `set -e`'s reach.
attempt=0
until LIBGIT2_SYS_USE_PKG_CONFIG=1 run output-1.90.0-$T/cargo; do
  attempt=$((attempt + 1))
  if [ "$attempt" -gt 4 ]; then
    echo "!!! cargo build still failing after $attempt attempts" >&2
    exit 1
  fi
  echo "--- cargo build failed; mirroring host OUT_DIRs (attempt $attempt) and retrying ---"
  symlink_outdirs
done
echo "=== DONE ==="
ls -la output-1.90.0-$T/rustc output-1.90.0-$T/cargo
