#!/bin/sh
# Minimal Rust project: cargo build, run (if rust/cargo available).

. "$(dirname "$0")/../common.sh"

# brew: need bash for shell commands (vdso_time SIGSEGV issue resolved by absolute path fix)
# coreutils for ls/mkdir/etc (host paths filtered from PATH in brew namespace)
# gcc for linker (cargo needs cc linker)
# Install all packages in one command to avoid symlink conflicts (re-install fails if symlinks exist)
if [ "$OS" = "brew" ]; then
    run_install rust cargo rustc gcc bash coreutils
else
    run_install rust cargo rustc
fi

check_cmd cargo --version || lang_skip "no rust package for OS=$OS"

run_ebin cargo --version

# msys2/conda on Windows have bash but no /bin/sh
# brew: host /bin/sh fails in namespace (vdso_time SIGSEGV), use brew's bash
if [ "$OS" = "msys2" ] || [ "$OS" = "conda" ]; then
    SHELL_CMD="bash -c"
elif [ "$OS" = "brew" ]; then
    SHELL_CMD="bash -c"
else
    SHELL_CMD="/bin/sh -c"
fi

run $SHELL_CMD "mkdir -p $TEST_TMP/rustproj/src && cd $TEST_TMP/rustproj && printf '%s\n' '[package]' 'name=\"rustproj\"' 'version=\"0.1.0\"' '[profile.release]' 'opt-level=0' > Cargo.toml"
run $SHELL_CMD "cd $TEST_TMP/rustproj && cat > src/main.rs << EOF
fn main() { println!(\"ok\"); }
EOF"
run $SHELL_CMD "cd $TEST_TMP/rustproj && cargo build && cargo run" | grep -q ok
run $SHELL_CMD "cd $TEST_TMP/rustproj && cargo add rand && cat > src/main.rs << EOF
fn main() { println!(\"{}\", rand::random::<u32>());
}
EOF"
run $SHELL_CMD "cd $TEST_TMP/rustproj && cargo run" | grep -q .
# Exercise ebin for cargo (build in rustproj)
# Use epkg run instead of direct ebin execution to ensure namespace isolation
# for resolving linker (cc/gcc) paths during build script compilation
if [ -n "${ENV_ROOT:-}" ] && [ -x "$ENV_ROOT/ebin/cargo" ]; then
    run $SHELL_CMD "cd $TEST_TMP/rustproj && cargo build"
fi
lang_ok