# # MIT License
#
# Copyright (c) 2020 Hiroaki Yutani
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Copied from <https://yutannihilation.github.io/string2path>.

# Variables used for tweaking Makevars
BEFORE_CARGO_BUILD=''

# Even when `cargo` is on `PATH`, `rustc` might not. We need to source
# ~/.cargo/env to ensure PATH is configured correctly in some cases
# (c.f. yutannihilation/string2path#4). However, this file is not always
# available (e.g. when Rust is installed via apt on Ubuntu), so it might be
# more straightforward to add `PATH` directly.
if [ -e "${HOME}/.cargo/env" ]; then
  . "${HOME}/.cargo/env"
  BEFORE_CARGO_BUILD="${BEFORE_CARGO_BUILD} . \"${HOME}/.cargo/env\" \\&\\&"
fi

# Check the Rust installation, and abort if not available
"${R_HOME}/bin/Rscript" "./tools/configure.R"

ret=$?

if [ $ret -ne 0 ]; then
  exit $ret
fi

# Report the version of Rustc to comply with the CRAN policy
echo "using Rust package manager: '$(cargo --version)'"
echo "using Rust compiler: '$(rustc --version)'"

# Handle webR
if [ "$(uname)" = "Emscripten" ]; then
  TARGET="wasm32-unknown-emscripten"
# If it's on CRAN, a package is not allowed to write in any other place than the
# temporary directory on installation. So, we need to tweak Makevars to make the
# compilation happen only within the package directory (i.e. `$(PWD)`).
elif [ "${DEBUG}" != "true" ]; then
  BEFORE_CARGO_BUILD="${BEFORE_CARGO_BUILD}"' export CARGO_HOME="$(PWD)/.cargo" \&\&'
  VENDORING="yes"
  OFFLINE_OPTION="--offline"
else
  echo "*** Detected DEBUG=true, do not override CARGO_HOME"
fi

sed \
  -e "s|@BEFORE_CARGO_BUILD@|${BEFORE_CARGO_BUILD}|" \
  -e "s|@VENDORING@|${VENDORING}|" \
  -e "s|@OFFLINE_OPTION@|${OFFLINE_OPTION}|" \
  -e "s|@TARGET@|${TARGET}|" \
  src/Makevars.in > src/Makevars

# Uncomment this to debug
#
# cat src/Makevars
