#!/usr/bin/env bash
set -euo pipefail

export CARGO_TARGET_DIR="$DERIVED_FILE_DIR/cargo"
export RUSTC="$(rustup which --toolchain stable rustc)"
export RUSTDOC="$(rustup which --toolchain stable rustdoc)"

if [[ "$CONFIGURATION" == "Debug" ]]; then
    profile=debug
else
    profile=release
fi

libraries=()
for arch in $ARCHS; do
    if [[ "$arch" == "arm64" && "${LLVM_TARGET_TRIPLE_SUFFIX:-}" == "-simulator" ]]; then
        target=aarch64-apple-ios-sim
    elif [[ "$arch" == "arm64" ]]; then
        target=aarch64-apple-ios
    elif [[ "$arch" == "x86_64" ]]; then
        target=x86_64-apple-ios
    else
        echo "Unsupported iOS architecture: $arch" >&2
        exit 1
    fi

    if [[ "$profile" == "debug" ]]; then
        rustup run stable cargo build --locked \
            --target "$target" --package ironstorage-apple --lib
    else
        rustup run stable cargo build --locked --release \
            --target "$target" --package ironstorage-apple --lib
    fi
    libraries+=("$CARGO_TARGET_DIR/$target/$profile/libironstorage_apple.a")
done

mkdir -p "$DERIVED_FILE_DIR/rust"
lipo -create -output "$DERIVED_FILE_DIR/rust/libironstorage_apple.a" "${libraries[@]}"
