#!/usr/bin/env bash
# swap-rust-into-toolchain.sh — overlay the hammer-built rust 1.91.1 onto a toolchain
# dir (default .dev-fs/alpine), so `hammer build` / `bootstrap stage1` compile the
# 4/4 rust inputs (arje-zero, hammerd) with hammer-rust instead of Alpine's rustc.
#
# This is the rust tool-swap of the selfhost-verify "variante b". Unlike make/bwrap/…
# (tools that orchestrate/copy → identical bytes), **rustc emits the 4/4 binaries**, so
# a hammer-built rustc produces a DIFFERENT of_tree than Alpine's 9adefb82. Success
# criterion is therefore AUTO-CONSISTENCY: stage1' built with hammer-rust == stage1''
# rebuilt with hammer-rust (a NEW EXPECT_REF), not byte-identity with the Alpine baseline.
#
# The overlay is mostly ADDITIVE and fully reversible:
#   - hammer's rustc/cargo use host triple x86_64-unknown-linux-musl and hash-suffixed
#     .so names that DON'T collide with Alpine's (x86_64-alpine-linux-musl / other
#     hashes), so the new rustlib triple + librustc_driver just sit alongside Alpine's.
#   - only /usr/bin/{rustc,cargo} are REPLACED; the originals are backed up to
#     usr/bin/<name>.alpine so `--restore` can put them back.
# The 4/4 rust recipes build NATIVE (target x86_64-linux-musl == SANDBOX_NATIVE_TARGET
# ⇒ no --target, see hammer-build/src/lib.rs:269), so hammer-rustc compiles them for
# its OWN native triple x86_64-unknown-linux-musl.
#
# Usage:
#   swap-rust-into-toolchain.sh [--prefix DIR] [--toolchain DIR]   # apply the swap
#   swap-rust-into-toolchain.sh --restore [--toolchain DIR]        # undo it
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
PREFIX="$ROOT/.scratch/rust-1.91.1-prefix"
TOOLCHAIN="$ROOT/.dev-fs/alpine"
RESTORE=0
while [ $# -gt 0 ]; do
    case "$1" in
        --prefix)    PREFIX="$2"; shift 2 ;;
        --toolchain) TOOLCHAIN="$2"; shift 2 ;;
        --restore)   RESTORE=1; shift ;;
        *) echo "uso: $0 [--prefix DIR] [--toolchain DIR] [--restore]" >&2; exit 2 ;;
    esac
done

say() { printf '\033[1;36m==> %s\033[0m\n' "$*"; }
die() { printf '\033[1;31mERROR: %s\033[0m\n' "$*" >&2; exit 1; }

[ -d "$TOOLCHAIN/usr/bin" ] || die "no veo el toolchain en $TOOLCHAIN"

if [ "$RESTORE" = 1 ]; then
    say "restaurar el rust de Alpine en $TOOLCHAIN"
    for b in rustc cargo; do
        if [ -f "$TOOLCHAIN/usr/bin/$b.alpine" ]; then
            mv -f "$TOOLCHAIN/usr/bin/$b.alpine" "$TOOLCHAIN/usr/bin/$b"
            echo "    restaurado usr/bin/$b"
        else
            echo "    (sin backup de usr/bin/$b — ¿ya restaurado?)"
        fi
    done
    # Quitar también lo AÑADIDO por el swap: el librustc_driver de hammer (hash propio, distinto del
    # de Alpine) y el sysroot del triple x86_64-unknown-linux-musl (un devfs Alpine prístino NO los
    # tiene). Inertes para el rustc de Alpine, pero dejarlos es ~350 MB de cruft y deja el toolchain
    # no-prístino; lo limpiamos para que --restore sea reversibilidad total.
    rm -rf "$TOOLCHAIN/usr/lib/rustlib/x86_64-unknown-linux-musl"
    # Sólo los librustc_driver que NO son de Alpine (Alpine deja exactamente uno; el swap añadió otro).
    if [ -d "$PREFIX/lib" ]; then
        for so in "$PREFIX"/lib/librustc_driver-*.so; do
            [ -e "$so" ] && rm -f "$TOOLCHAIN/usr/lib/$(basename "$so")"
        done
    fi
    echo "    limpiado usr/lib/rustlib/x86_64-unknown-linux-musl + librustc_driver de hammer"
    exit 0
fi

[ -x "$PREFIX/bin/rustc" ] || die "no veo el prefix hammer-rust en $PREFIX (corré el climb primero)"

say "swap: overlay hammer-rust 1.91.1 ($PREFIX) → $TOOLCHAIN"

# 1) librustc_driver de hammer (hash único, no choca con el de Alpine).
cp -a "$PREFIX"/lib/librustc_driver-*.so "$TOOLCHAIN/usr/lib/"
echo "    + usr/lib/$(basename "$PREFIX"/lib/librustc_driver-*.so)"

# 2) sysroot de hammer para su triple nativo (dir nuevo, no choca con x86_64-alpine-linux-musl).
rm -rf "$TOOLCHAIN/usr/lib/rustlib/x86_64-unknown-linux-musl"
cp -a "$PREFIX/lib/rustlib/x86_64-unknown-linux-musl" "$TOOLCHAIN/usr/lib/rustlib/"
echo "    + usr/lib/rustlib/x86_64-unknown-linux-musl ($(du -sh "$PREFIX/lib/rustlib/x86_64-unknown-linux-musl" | cut -f1))"

# 3) reemplazar rustc y cargo (backup de los de Alpine).
for b in rustc cargo; do
    [ -f "$TOOLCHAIN/usr/bin/$b.alpine" ] || cp -a "$TOOLCHAIN/usr/bin/$b" "$TOOLCHAIN/usr/bin/$b.alpine"
    cp -a "$PREFIX/bin/$b" "$TOOLCHAIN/usr/bin/$b"
    echo "    ~ usr/bin/$b  (Alpine guardado en usr/bin/$b.alpine)"
done

say "listo. verificá con:  bwrap --bind $TOOLCHAIN / ... /usr/bin/rustc --version"
echo "    esperado: rustc 1.91.1 (ed61e7d7e …) host x86_64-unknown-linux-musl"
echo "    deshacer: $0 --restore --toolchain $TOOLCHAIN"
