# Even when `cargo` is on `PATH`, `rustc` might not in some cases. This adds
# ~/.cargo/bin to PATH to address such cases. Note that is not always available
# (e.g. or on Ubuntu with Rust installed via APT).
if [ -d "${HOME}/.cargo/bin" ]; then
  export PATH="${PATH}:${HOME}/.cargo/bin"
fi

CARGO_VERSION="$(cargo --version)"

if [ $? -ne 0 ]; then
  echo "-------------- ERROR: CONFIGURATION FAILED --------------------"
  echo ""
  echo "The cargo command is not available. To install Rust, please refer"
  echo "to the official instruction:"
  echo ""
  echo "https://www.rust-lang.org/tools/install"
  echo ""
  echo "---------------------------------------------------------------"

  exit 1
fi

# There's a little chance that rustc is not available on PATH while cargo is.
# So, just ignore the error case.
RUSTC_VERSION="$(rustc --version || true)"

# Report the version of Rustc to comply with the CRAN policy
echo "using Rust package manager: '${CARGO_VERSION}'"
echo "using Rust compiler: '${RUSTC_VERSION}'"

if [ "$(uname)" = "Emscripten" ]; then
  TARGET="wasm32-unknown-emscripten"
fi

# allow overriding profile externally (e.g. on CI)
if [ -n "${SAVVY_PROFILE}" ]; then
  PROFILE="${SAVVY_PROFILE}"
# catch DEBUG envvar, which is passed from pkgbuild::compile_dll()
elif [ "${DEBUG}" = "true" ]; then
  PROFILE=dev
else
  PROFILE=release
fi

# e.g. SAVVY_FEATURES="a b"  -->  "--features 'a b'"
if [ -n "${SAVVY_FEATURES}" ]; then
  FEATURE_FLAGS="--features '${SAVVY_FEATURES}'"
fi

# Set macOS deployment target for the Rust cc crate.
#
# The cc crate (used by savvy's build.rs to compile unwind_protect_wrapper.c)
# does not derive the deployment target from CC/CFLAGS. Instead, it looks up
# MACOSX_DEPLOYMENT_TARGET, falling back to `xcrun --show-sdk-version`, and
# passes the result as -mmacosx-version-min=<value>. When the env var is unset,
# the fallback SDK version (e.g. 26.2) can be newer than the version R's
# compiler targets, producing an ld warning about version mismatch.
#
# We default to 11.0, the minimum deployment target for arm64 macOS. This
# should be safe because unwind_protect_wrapper.c is a fairly simple C code
# and uses no version-specific APIs.
if [ "$(uname)" = "Darwin" ]; then
  MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-11.0}"
  echo "using macOS deployment target: ${MACOSX_DEPLOYMENT_TARGET}"
  BEFORE_CARGO_BUILD="${BEFORE_CARGO_BUILD}"' export MACOSX_DEPLOYMENT_TARGET="'"${MACOSX_DEPLOYMENT_TARGET}"'" \&\&'
fi

# --- spice: vendored sources (CRAN) --------------------------------
# tools/r-vendor.sh writes src/rust/vendor.tar.xz (crates.io sources +
# the dune engine crates); with it the build is offline (Makevars).
if [ -f "src/rust/vendor.tar.xz" ]; then
  VENDORED=1
  CARGO_OFFLINE="--offline -j 2"
  echo "using vendored Rust sources: src/rust/vendor.tar.xz (offline build)"
else
  VENDORED=0
  CARGO_OFFLINE=""
fi

# --- spice: locate the dune engine crates -------------------------
# Inside the dune repository src/rust/Cargo.toml points at
# ../../../crates/*. Away from it (an unpacked tarball) the paths are
# rewritten to the vendored copy (src/dune, unpacked by Makevars from
# the vendor archive) or, without one, to DUNE_ROOT (the root of a
# dune checkout; the repository's CI check does this).
if [ ! -f "src/rust/../../../crates/dune-core/Cargo.toml" ]; then
  if [ "${VENDORED}" = "1" ]; then
    DUNE_CRATES="../dune/crates/"
  elif [ -n "${DUNE_ROOT}" ] && [ -f "${DUNE_ROOT}/crates/dune-core/Cargo.toml" ]; then
    echo "using dune crates from DUNE_ROOT: '${DUNE_ROOT}'"
    DUNE_CRATES="${DUNE_ROOT}/crates/"
  else
    echo "-------------- ERROR: CONFIGURATION FAILED --------------------"
    echo ""
    echo "The dune engine crates were not found next to the package, and"
    echo "src/rust/vendor.tar.xz is missing. Build from the dune repository"
    echo "(r/), run tools/r-vendor.sh there before R CMD build, or set"
    echo "DUNE_ROOT to the root of a dune checkout."
    echo ""
    echo "---------------------------------------------------------------"
    exit 1
  fi
  sed -e "s|\.\./\.\./\.\./crates/|${DUNE_CRATES}|g" \
    src/rust/Cargo.toml > src/rust/Cargo.toml.tmp && \
    mv src/rust/Cargo.toml.tmp src/rust/Cargo.toml
fi

# --- spice: cargo's own target directory ---------------------------
# Vendored (CRAN): src/rust/target, removed after the build — nothing
# is written outside the package directory. Otherwise honour
# CARGO_TARGET_DIR and the user's cargo config (target-dir); cargo's
# default is src/rust/target.
if [ "${VENDORED}" = "1" ]; then
  TARGET_DIR="$(pwd)/src/rust/target"
  CLEAN_TARGET='$(TARGET_DIR)'
else
  CARGO_METADATA=$(cd src/rust && cargo metadata --format-version 1 --no-deps --offline 2>/dev/null)
  TARGET_DIR=$(printf '%s' "${CARGO_METADATA}" | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')
  if [ -z "${TARGET_DIR}" ]; then
    TARGET_DIR="$(pwd)/src/rust/target"
  fi
  CLEAN_TARGET=""
fi
echo "using cargo target directory: '${TARGET_DIR}'"

sed \
  -e "s|@TARGET_DIR@|${TARGET_DIR}|" \
  -e "s/@TARGET@/${TARGET}/" \
  -e "s/@PROFILE@/${PROFILE}/" \
  -e "s/@FEATURE_FLAGS@/${FEATURE_FLAGS}/" \
  -e "s/@VENDORED@/${VENDORED}/" \
  -e "s/@CARGO_OFFLINE@/${CARGO_OFFLINE}/" \
  -e "s/@CLEAN_TARGET@/${CLEAN_TARGET}/" \
  -e "s|@BEFORE_CARGO_BUILD@|${BEFORE_CARGO_BUILD}|" \
  src/Makevars.in > src/Makevars
