#!/bin/sh

set -eu

# Xcode 26's downloadable Metal toolchain is mounted as a read-only Cryptex.
# xcrun normally discovers it through MobileAsset, but that lookup is not
# available to sandboxed build runners. Invoke the mounted driver directly for
# Metal commands and preserve normal xcrun behavior for everything else.
if [ "$#" -ge 3 ] && [ "$1" = "-sdk" ] && [ "$2" = "macosx" ]; then
    bt_requested_tool=$3

    if [ "$bt_requested_tool" = "metal" ] || [ "$bt_requested_tool" = "metallib" ]; then
        bt_metal_driver=""
        for bt_candidate in \
            /var/run/com.apple.security.cryptexd/mnt/com.apple.MobileAsset.MetalToolchain-*/Metal.xctoolchain/usr/bin/metal
        do
            if [ -x "$bt_candidate" ]; then
                bt_metal_driver=$bt_candidate
                break
            fi
        done

        if [ -n "$bt_metal_driver" ]; then
            shift 3

            if [ "$bt_requested_tool" = "metal" ]; then
                bt_module_cache=${BT_METAL_MODULE_CACHE:-/private/tmp/banjo-tooie-recompiled-metal-modules}
                mkdir -p "$bt_module_cache"
                exec "$bt_metal_driver" \
                    "-fmodules-cache-path=$bt_module_cache" "$@"
            fi

            # The Xcode 26 metal driver links AIR inputs directly and replaces
            # the separate `metallib` frontend used by older Xcode releases.
            exec "$bt_metal_driver" "$@"
        fi
    fi
fi

exec /usr/bin/xcrun "$@"
