#!/bin/sh
# Configure script for fdars R package
# Checks for Rust toolchain availability

# Check for cargo
if ! command -v cargo >/dev/null 2>&1; then
    echo "-----------------------------------------------------"
    echo "ERROR: Rust toolchain not found."
    echo ""
    echo "This package requires the Rust programming language."
    echo "Please install Rust from: https://rustup.rs/"
    echo ""
    echo "On most systems, you can install Rust with:"
    echo "  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
    echo ""
    echo "After installation, restart your terminal and try again."
    echo "-----------------------------------------------------"
    exit 1
fi

# Check Rust version
RUST_VERSION=$(rustc --version 2>/dev/null | cut -d' ' -f2)
echo "Found Rust version: $RUST_VERSION"

# Check minimum version (1.81)
RUST_MAJOR=$(echo $RUST_VERSION | cut -d'.' -f1)
RUST_MINOR=$(echo $RUST_VERSION | cut -d'.' -f2)

if [ "$RUST_MAJOR" -lt 1 ] || ([ "$RUST_MAJOR" -eq 1 ] && [ "$RUST_MINOR" -lt 81 ]); then
    echo "-----------------------------------------------------"
    echo "ERROR: Rust version $RUST_VERSION is too old."
    echo ""
    echo "This package requires Rust >= 1.81"
    echo "Please update Rust with: rustup update"
    echo "-----------------------------------------------------"
    exit 1
fi

# Restore .cargo-checksum.json files for vendored builds
# These are shipped without the dot prefix to avoid R CMD check hidden files NOTE
for f in src/rust/vendor/*/cargo-checksum.json; do
    if [ -f "$f" ]; then
        mv "$f" "$(dirname "$f")/.cargo-checksum.json"
    fi
done

# Generate src/Makevars from template with platform-specific linker flags
# GNU ld supports --version-script and --wrap to hide/intercept symbols
# that R CMD check flags (abort, exit, _exit). macOS ld does not.
WRAP_FLAGS=""
if [ "$(uname -s)" = "Linux" ]; then
    WRAP_FLAGS="-Wl,--version-script=\$(CURDIR)/symbols.map -Wl,--wrap=abort -Wl,--wrap=exit -Wl,--wrap=_exit"
fi
sed "s|@WRAP_FLAGS@|${WRAP_FLAGS}|g" src/Makevars.in > src/Makevars

echo "Rust toolchain OK"
exit 0
