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

readonly REAL_CARGO=/opt/rust/cargo/bin/cargo
readonly TARGET=x86_64-pc-windows-gnu

if [[ "${1:-}" != build ]]; then
    exec "$REAL_CARGO" "$@"
fi

"$REAL_CARGO" "$@" --target "$TARGET"

# The project CMake imports the Rust static library from the native profile
# path, but a targeted build puts it one directory deeper. Mirror it there.
: "${CARGO_TARGET_DIR:?CARGO_TARGET_DIR must be set by the project CMake build}"
profile=debug
for arg in "$@"; do
    if [[ "$arg" == --release ]]; then
        profile=release
        break
    fi
done

source_lib="$CARGO_TARGET_DIR/$TARGET/$profile/libmatrix_client_rust.a"
target_lib="$CARGO_TARGET_DIR/$profile/libmatrix_client_rust.a"
test -f "$source_lib"
install -Dm0644 "$source_lib" "$target_lib"
