# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

# We need to link GEOS libs. The cargo build will use pkg-config
# and then geos-config, in that order, and requires pkg-config to be
# available (even if it isn't used). Here we just try pkg-config (LIB_DIR
# can be used to specify the location of -lgeos_c)

pkg-config geos  2>/dev/null
if [ $? -eq 0 ]; then
  PKGCONFIG_LIBS=`pkg-config --libs geos`
fi

if [ "$LIB_DIR" ]; then
  echo "Found LIB_DIR!"
  PKG_LIBS="-L$LIB_DIR -lgeos_c $PKG_LIBS"
elif [ "$PKGCONFIG_CFLAGS" ] || [ "$PKGCONFIG_LIBS" ]; then
  echo "Found GEOS pkg-config libs!"
  PKG_LIBS=${PKGCONFIG_LIBS}
fi


# 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

# Guard against `cargo` resolving to the rustup-init installer. When the
# rustup proxy can't find its install state it identifies as "rustup-init"
# and rejects normal cargo subcommands like `build` and `metadata`, which
# surfaces as a misleading "unexpected argument 'build'" failure deep in
# the Make recipe. Fail fast with the real diagnosis. See sedona-db#837.
case "$CARGO_VERSION" in
  rustup-init*)
    echo "-------------- ERROR: CONFIGURATION FAILED --------------------"
    echo ""
    echo "'cargo' on PATH is the rustup-init installer, not the rustup"
    echo "proxy. cargo --version reports:"
    echo "    $CARGO_VERSION"
    echo ""
    echo "Ensure \$HOME/.cargo/bin is ahead of any other Rust installer"
    echo "on PATH (e.g. Homebrew rustup), or reinstall the stable toolchain"
    echo "with: rustup toolchain install stable && rustup default stable"
    echo ""
    echo "---------------------------------------------------------------"

    exit 1
    ;;
esac

# 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

# On macOS, prefer Homebrew's mutually compatible S2, Abseil, and OpenSSL
# packages. On other Unix platforms CMake will use a system S2 package when
# available and otherwise build the vendored s2geometry source.
S2_VCPKG_ROOT="${VCPKG_ROOT}"
S2_VCPKG_DEFAULT_TRIPLET="${VCPKG_DEFAULT_TRIPLET}"
S2_VCPKG_TARGET_TRIPLET="${VCPKG_TARGET_TRIPLET:-${VCPKG_DEFAULT_TRIPLET}}"
S2_VCPKG_OVERLAY_TRIPLETS="${VCPKG_OVERLAY_TRIPLETS}"
S2_VCPKG_MANIFEST_MODE="${VCPKG_MANIFEST_MODE}"
S2_CMAKE_TOOLCHAIN_FILE="${CMAKE_TOOLCHAIN_FILE}"
S2_CMAKE_PREFIX_PATH="${CMAKE_PREFIX_PATH}"
S2_OPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}"

S2_VCPKG_ENABLED=false
if [ -n "${S2_VCPKG_ROOT}" ] && \
    [ -f "${S2_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" ]; then
  S2_VCPKG_ENABLED=true
fi
if [ "${S2_VCPKG_ENABLED}" = true ] && [ -z "${S2_CMAKE_TOOLCHAIN_FILE}" ]; then
  S2_CMAKE_TOOLCHAIN_FILE="${S2_VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
fi

SAVVY_FEATURE_WORDS="$(printf '%s' "${SAVVY_FEATURES}" | tr ',' ' ')"
case " ${SAVVY_FEATURE_WORDS} " in
  *" s2geography "*)
    if [ "${S2_VCPKG_ENABLED}" = true ]; then
      echo "using vcpkg dependencies from ${S2_VCPKG_ROOT}"
    elif [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
      for formula in s2geometry abseil openssl@3; do
        formula_prefix="$(brew --prefix "${formula}" 2>/dev/null)" || {
          echo "-------------- ERROR: CONFIGURATION FAILED --------------------"
          echo ""
          echo "Building with SAVVY_FEATURES=s2geography on macOS requires"
          echo "the Homebrew packages s2geometry, abseil, and openssl@3."
          echo "Install them with: brew install s2geometry abseil openssl@3"
          echo ""
          echo "---------------------------------------------------------------"
          exit 1
        }
        if [ -n "${S2_CMAKE_PREFIX_PATH}" ]; then
          S2_CMAKE_PREFIX_PATH="${S2_CMAKE_PREFIX_PATH};${formula_prefix}"
        else
          S2_CMAKE_PREFIX_PATH="${formula_prefix}"
        fi
      done
      echo "using Homebrew s2geometry, Abseil, and OpenSSL"
    fi
    ;;
esac

sed \
  -e "s/@TARGET@/${TARGET}/" \
  -e "s/@PROFILE@/${PROFILE}/" \
  -e "s/@FEATURE_FLAGS@/${FEATURE_FLAGS}/" \
  -e "s|@VCPKG_ROOT@|${S2_VCPKG_ROOT}|" \
  -e "s|@VCPKG_DEFAULT_TRIPLET@|${S2_VCPKG_DEFAULT_TRIPLET}|" \
  -e "s|@VCPKG_TARGET_TRIPLET@|${S2_VCPKG_TARGET_TRIPLET}|" \
  -e "s|@VCPKG_OVERLAY_TRIPLETS@|${S2_VCPKG_OVERLAY_TRIPLETS}|" \
  -e "s|@VCPKG_MANIFEST_MODE@|${S2_VCPKG_MANIFEST_MODE}|" \
  -e "s|@CMAKE_TOOLCHAIN_FILE@|${S2_CMAKE_TOOLCHAIN_FILE}|" \
  -e "s|@CMAKE_PREFIX_PATH@|${S2_CMAKE_PREFIX_PATH}|" \
  -e "s|@OPENSSL_ROOT_DIR@|${S2_OPENSSL_ROOT_DIR}|" \
  -e "s|@PKG_LIBS@|${PKG_LIBS}|" \
  src/Makevars.in > src/Makevars
