#!/bin/sh
# zig cc wrapper for cross builds that involve cmake-based crates (boring-sys).
#
# Under cross compilation CMake injects clang-style target flags
# (`--target=<triple>` in flags, `-target <triple>` right after the compiler)
# into the ASM rule (boring-sys sets CMAKE_*_COMPILER_TARGET). Real GCC
# rejects the option and zig rejects the Rust triple spelling
# (`x86_64-unknown-linux-musl` vs zig's `x86_64-linux-musl`). This wrapper
# strips every target flag form and re-anchors on the zig-style target from
# $ZIGCC_TARGET.
#
# Usage:
#   ZIGCC_TARGET=x86_64-linux-musl \
#   CC_x86_64_unknown_linux_musl=/path/to/ci/zigcc \
#   CXX_x86_64_unknown_linux_musl=/path/to/ci/zigcxx \
#   CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER=/path/to/ci/zigcc \
#   cargo build --target x86_64-unknown-linux-musl ...
#
# Note: the filtered args are intentionally re-split on newlines — CMake and
# compiler invocations pass them pre-split and none contain spaces here.
if [ -z "$ZIGCC_TARGET" ]; then
    echo "zigcc: ZIGCC_TARGET is not set (e.g. x86_64-linux-musl)" >&2
    exit 1
fi

kept=
skip_next=0
for arg in "$@"; do
    if [ "$skip_next" = 1 ]; then
        skip_next=0
        continue
    fi
    case "$arg" in
        --target=*) ;;
        -target | --target) skip_next=1 ;;
        # rustc passes these for aarch64-linux-gnu; zig's linker driver
        # rejects them (lld handles the errata workarounds itself).
        -Wl,--fix-cortex-a53-843419 | -Wl,--fix-cortex-a53-835769) ;;
        *)
            kept="$kept
$arg"
            ;;
    esac
done

# shellcheck disable=SC2046
exec zig cc -target "$ZIGCC_TARGET" $(printf '%s' "$kept" | tail -n +2)
