#!/usr/bin/env bash
# Preserve normal Cargo target/linker flags and normalize embedded source paths.
source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh"
cd "$FDS_ROOT"
fds_cargo_home=${CARGO_HOME:-$HOME/.cargo}
fds_rustup_home=${RUSTUP_HOME:-$HOME/.rustup}
mappings=("$FDS_ROOT=/usr/src/fds" "$fds_rustup_home=/usr/src/fds/rustup")
for registry in "$fds_cargo_home"/registry/src/*; do
    [[ -d $registry ]] || continue
    mappings+=("$registry=/usr/src/fds/crates")
done
flags=
for mapping in "${mappings[@]}"; do
    # This creates TOML data passed as one argument, not executable shell text.
    escaped=${mapping//\\/\\\\}
    escaped=${escaped//\"/\\\"}
    flags+="\"--remap-path-prefix=$escaped\","
done
# Cargo merges these arrays with the configured target flags, including static
# CRT and self-contained linking. The flags participate in Cargo's cache key.
exec cargo \
    --config "target.aarch64-unknown-linux-musl.rustflags=[$flags]" \
    --config "target.x86_64-unknown-linux-gnu.rustflags=[$flags]" \
    build "$@"
