#!/usr/bin/env sh

NOT_CRAN=${NOT_CRAN:-"false"}
LIBPRQLR_BUILD=${LIBPRQLR_BUILD:-""}

# Detect if this is on R-universe.
MY_UNIVERSE=${MY_UNIVERSE:-""}

LIBNAME="libprqlr.a"
LIBPRQLR_DEFAULT_PATH="$(pwd)/tools/${LIBNAME}"
LIBPRQLR_PATH=${LIBPRQLR_PATH:-${LIBPRQLR_DEFAULT_PATH}}

export PATH="$PATH:$HOME/.cargo/bin"

check_cargo() {
  if [ ! "$(command -v cargo)" ]; then
    cat <<EOF
------------------------- [RUST NOT FOUND] -------------------------
The 'cargo' command was not found on the PATH. Please install rustc
from: https://www.rust-lang.org/tools/install

Alternatively, you may install cargo from your OS package manager:
  - Debian/Ubuntu: apt-get install cargo
  - Fedora/CentOS: dnf install cargo
  - macOS: brew install rustc
--------------------------------------------------------------------
EOF
    exit 1
  else
    cat <<EOF
--------------------------- [RUST FOUND] ---------------------------
$(cargo -V)

$(rustc -vV)
--------------------------------------------------------------------
EOF
  fi
}

check_bin_lib() {
  if [ "${NOT_CRAN}" = "true" ] && [ -z "${LIBPRQLR_BUILD}" ]; then
    LIBPRQLR_BUILD="false"
  fi

  # On R-universe, we try to download the pre-built binary from GitHub releases.
  if [ -n "${MY_UNIVERSE}" ] && [ -z "${LIBPRQLR_BUILD}" ]; then
    cat <<EOF
--------------------- [SETTING FOR R-UNIVERSE] ---------------------
It seems that this is on R-universe <${MY_UNIVERSE}>.
Trying to download pre-built binary.
--------------------------------------------------------------------
EOF
    LIBPRQLR_BUILD="false"
  fi

  if [ "${LIBPRQLR_BUILD}" = "false" ]; then
    if [ -f "tools/lib-sums.tsv" ] && [ ! -f "${LIBPRQLR_PATH}" ]; then
      cat <<EOF
---------------- [TRY TO DOWNLOAD PRE-BUILT BINARY] ----------------
The library was not found at <${LIBPRQLR_PATH}>.
Trying to download pre-built binary from the Internet...
--------------------------------------------------------------------
EOF
      "${R_HOME}/bin${R_ARCH_BIN}/Rscript" "tools/prep-lib.R" && echo "Done!" ||
        echo "Failed to download pre-built binary."
    fi

    if [ -f "${LIBPRQLR_PATH}" ] && [ "${LIBPRQLR_PATH}" != "${LIBPRQLR_DEFAULT_PATH}" ]; then
      cat <<EOF
------------------------- [COPYING BINARY] -------------------------
Copying <${LIBPRQLR_PATH}> to <${LIBPRQLR_DEFAULT_PATH}>.
--------------------------------------------------------------------
EOF
      $(mkdir -p "$(dirname "${LIBPRQLR_DEFAULT_PATH}")")
      $(cp "${LIBPRQLR_PATH}" "${LIBPRQLR_DEFAULT_PATH}" && echo "Done!" || echo "Failed to copy binary.")
    fi

    if [ -f "${LIBPRQLR_DEFAULT_PATH}" ]; then
      cat <<EOF
---------------------- [LIBRARY BINARY FOUND] ----------------------
The library was found at <${LIBPRQLR_DEFAULT_PATH}>. No need to build it.

Note: rustc version: $(command -v rustc >/dev/null && rustc -V || echo "Not found")
--------------------------------------------------------------------
EOF
      sed -e "s|@RUST_TARGET@||" src/Makevars.in >src/Makevars
      exit 0
    fi
    cat <<EOF
-------------------- [LIBRARY BINARY NOT FOUND] --------------------
The library was not found at <${LIBPRQLR_PATH}>.
Falling back to building from source.
--------------------------------------------------------------------
EOF
  fi
}

detect_target_option() {
  for option in "$@"; do
    case "${option}" in
    --host=*)
      specified_target="$(echo "${option}" | sed -e 's/--host=//' | sed -E 's/([0-9]+\.)*[0-9]+$//')"
      cat <<EOF
------------------------ [DETECTED TARGET] ------------------------
The target was specified as <${specified_target}> via the '--host' option.
-------------------------------------------------------------------
EOF
      export TARGET="${specified_target}"
      ;;
    *) ;;
    esac
    shift
  done
}

check_msrv() {
  rustc_version="$(rustc -V | grep -o '[0-9]\+\(\.[0-9]\+\)\+')"
  package_rust_version="$(
    cargo metadata --manifest-path src/rust/Cargo.toml --no-deps --format-version 1 |
      grep -o '"rust_version"\s*:\s*"[0-9]\+\(\.[0-9]\+\)\+"' |
      grep -o '[0-9]\+\(\.[0-9]\+\)\+'
  )"
  lower_version="$(echo "${rustc_version} ${package_rust_version}" | tr ' ' '\n' | sort -V | head -n1)"

  if [ "${rustc_version}" != "${package_rust_version}" ] && [ "${rustc_version}" = "${lower_version}" ]; then
    cat <<EOF
------------------- [NOT SUPPORTED RUST VERSION] -------------------
The MSRV of this package is '${package_rust_version}',
so this installation may fail with the current rustc version '${rustc_version}'.
If this happens, please install the newer version of rustc
from: https://www.rust-lang.org/tools/install
--------------------------------------------------------------------
EOF
  else
    cat <<EOF
----------------- [MINIMUM SUPPORTED RUST VERSION] -----------------
The MSRV of this package is '${package_rust_version}'.
--------------------------------------------------------------------
EOF
  fi
}

detect_target_option "$@"
check_bin_lib
check_cargo
check_msrv

# cf. https://github.com/r-wasm/rwasm/issues/18#issuecomment-1910198843
if [ "$(uname)" = "Emscripten" ]; then
  HOST_TRIPLE="wasm32-unknown-emscripten"
else
  HOST_TRIPLE="$(rustc -vV | grep host | cut -d' ' -f2)"
fi

RUST_TARGET="${TARGET:-${HOST_TRIPLE}}"
sed \
  -e "s|@RUST_TARGET@|${RUST_TARGET}|" \
  src/Makevars.in >src/Makevars

exit 0
