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

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH:$HOME/.cargo/bin"
export RUSTC="$(rustup which --toolchain stable rustc)"
export RUSTDOC="$(rustup which --toolchain stable rustdoc)"
export CARGO_TARGET_DIR="$DERIVED_FILE_DIR/cargo"

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 gotcha-app --lib
    else
        rustup run stable cargo build --locked --release --target "$target" --package gotcha-app --lib
    fi
    libraries+=("$CARGO_TARGET_DIR/$target/$profile/libgotcha_core.a")
done

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