#!/bin/bash

# based on https://github.com/chinedufn/swift-bridge/tree/master/book/src/building/swift-packages

set -e

THISDIR=$(dirname $0)
cd $THISDIR

if [[ -f ~/.cargo/env ]];
then
  source ~/.cargo/env
fi

echo "Installing required components"

rustup +nightly component add rust-src
cargo install swift-bridge-cli --color always
#rustup component add rust-src --toolchain x86_64-apple-ios-macabi
#rustup component add rust-src --toolchain darwin-apple-ios-macabi

rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim

echo "Building stdlib for the desired platforms..."
#cargo build --target x86_64-apple-darwin
#cargo build --target aarch64-apple-darwin
cargo +nightly build -Z build-std --target x86_64-apple-ios-macabi --color always
cargo +nightly build -Z build-std --target aarch64-apple-ios-macabi --color always

BRIDGE_NAME=libmonal_rust_swift_bridge.a

echo "Creating catalyst target universal lib..."
mkdir -p ./target/catalyst-macos/debug
lipo \
    ./target/x86_64-apple-ios-macabi/debug/$BRIDGE_NAME \
    ./target/aarch64-apple-ios-macabi/debug/$BRIDGE_NAME \
    -create -output \
    ./target/catalyst-macos/debug/$BRIDGE_NAME

echo "Building rust code for all targets..."
cargo build --target aarch64-apple-ios --color always
cargo build --target x86_64-apple-ios --color always
cargo build --target aarch64-apple-ios-sim --color always

echo "Creating ios target universal lib..."
mkdir -p ./target/universal-ios/debug
lipo \
    ./target/aarch64-apple-ios-sim/debug/$BRIDGE_NAME \
    ./target/x86_64-apple-ios/debug/$BRIDGE_NAME \
    -create -output \
    ./target/universal-ios/debug/$BRIDGE_NAME

echo "Creating swift package..."
swift-bridge-cli create-package \
  --bridges-dir ./monal-rust-swift-bridge/generated \
  --out-dir LibMonalRustSwiftBridge \
  --ios target/aarch64-apple-ios/debug/$BRIDGE_NAME \
  --simulator target/universal-ios/debug/$BRIDGE_NAME \
  --mac-catalyst target/catalyst-macos/debug/$BRIDGE_NAME \
  --name LibMonalRustSwiftBridge

# copy over our own swift files
cp -av ./monal-rust-swift-bridge/swift/* LibMonalRustSwiftBridge/Sources/LibMonalRustSwiftBridge/ 

# make sure all autogenerated swift to rust wrapper functions are public
# TODO: maybe fix upstream?
sed -i '' 's/^func/public func/g' LibMonalRustSwiftBridge/Sources/LibMonalRustSwiftBridge/*.swift
