+# First we set various compiler flags...
+HOST_PLATFORM="$(rustc --version --verbose | grep "host:" | awk '{ print $2 }')"
+ENV_TARGET=$(echo $HOST_PLATFORM | sed 's/-/_/g')
+
+# Set path to include our rustc wrapper as well as cbindgen
+export LDK_RUSTC_PATH="$(which rustc)"
+export RUSTC="$(pwd)/deterministic-build-wrappers/rustc"
+PATH="$PATH:~/.cargo/bin"
+
+# Set up CFLAGS and RUSTFLAGS vars appropriately for building libsecp256k1 and demo apps...
+BASE_CFLAGS="" # CFLAGS for libsecp256k1
+LOCAL_CFLAGS="" # CFLAGS for demo apps
+
+# Remap paths so that our builds are deterministic
+BASE_RUSTFLAGS="--cfg=c_bindings --remap-path-prefix $LIGHTNING_PATH=rust-lightning --remap-path-prefix $(pwd)=ldk-c-bindings --remap-path-prefix $HOME/.cargo="
+
+# If the C compiler supports it, also set -ffile-prefix-map
+echo "int main() {}" > genbindings_path_map_test_file.c
+clang -o /dev/null -ffile-prefix-map=$HOME/.cargo= genbindings_path_map_test_file.c > /dev/null 2>&1 &&
+export BASE_CFLAGS="-ffile-prefix-map=$HOME/.cargo="
+
+BASE_CFLAGS="$BASE_CFLAGS -frandom-seed=42"
+LOCAL_CFLAGS="-Wall -Wno-nullability-completeness -pthread -Iinclude/"
+
+HOST_OSX=false
+if [ "$HOST_PLATFORM" = "x86_64-apple-darwin" ]; then
+ HOST_OSX=true
+elif [ "$HOST_PLATFORM" = "aarch64-apple-darwin" ]; then
+ HOST_OSX=true
+fi
+
+BASE_HOST_CFLAGS="$BASE_CFLAGS"
+
+if [ "$HOST_OSX" = "true" ]; then
+ export MACOSX_DEPLOYMENT_TARGET=10.9
+ LOCAL_CFLAGS="$LOCAL_CFLAGS --target=$HOST_PLATFORM -isysroot$(xcrun --show-sdk-path) -mmacosx-version-min=10.9"
+ BASE_HOST_CFLAGS="$BASE_HOST_CFLAGS --target=$HOST_PLATFORM -isysroot$(xcrun --show-sdk-path) -mmacosx-version-min=10.9"
+ # Targeting aarch64 appears to be supported only starting with Big Sur, so check it before use
+ clang -o /dev/null $BASE_HOST_CFLAGS --target=aarch64-apple-darwin -mcpu=apple-a14 genbindings_path_map_test_file.c &&
+ export CFLAGS_aarch64_apple_darwin="$BASE_HOST_CFLAGS --target=aarch64-apple-darwin -mcpu=apple-a14" ||
+ echo "WARNING: Can not build targeting aarch64-apple-darin. Upgrade to Big Sur or try upstream clang"
+fi
+
+rm genbindings_path_map_test_file.c
+
+case "$ENV_TARGET" in
+ "x86_64"*)
+ export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=sandybridge"
+ export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS -march=sandybridge -mcpu=sandybridge -mtune=sandybridge"
+ ;;
+ "aarch64_apple_darwin")
+ export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14"
+ export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS -mcpu=apple-a14"
+ ;;
+ *)
+ # Assume this isn't targeted at another host and build for the host's CPU.
+ export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=native"
+ export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS -mcpu=native"
+ ;;
+esac
+