#!/bin/sh
# configure for janssonr: link the system libjansson when a usable one
# (>= 2.11) is found, otherwise compile the bundled Jansson 2.15.1
# sources under src/jansson/ (CRAN's macOS builders ship no jansson).
# JANSSONR_VENDOR=1 (via --configure-vars) forces the bundled copy.
PKG_CONFIG_NAME="jansson"
PKG_MIN_VERSION="2.11"
PKG_MIN_VERSION_HEX="0x020b00"

: "${R_HOME=`R RHOME`}"
CC=`"${R_HOME}/bin/R" CMD config CC`
CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`

# Header usable AND floor holds under the given cpp flags (pipe, no
# temp files)
probe () {
  printf '#include <jansson.h>\n#if JANSSON_VERSION_HEX < %s\n#error too old\n#endif\n' \
       "$PKG_MIN_VERSION_HEX" | \
       $CC $CPPFLAGS $1 -E -xc - >/dev/null 2>&1
}

use_system=no
PKG_CFLAGS=""
PKG_LIBS=""

if [ -n "$JANSSONR_VENDOR" ]; then
  echo "JANSSONR_VENDOR set: using the bundled Jansson"
elif [ -n "$INCLUDE_DIR" ] || [ -n "$LIB_DIR" ]; then
  # explicit --configure-vars='INCLUDE_DIR=... LIB_DIR=...' override;
  # each side is independent so setting only one never emits an empty
  # -I or -L. An explicit ask that does not work is a hard error, not
  # a silent fall-through to the bundled copy.
  [ -n "$INCLUDE_DIR" ] && PKG_CFLAGS="-I$INCLUDE_DIR"
  [ -n "$LIB_DIR" ] && PKG_LIBS="-L$LIB_DIR -ljansson"
  [ -n "$LIB_DIR" ] || PKG_LIBS="-ljansson"
  if ! probe "$PKG_CFLAGS"; then
    echo "INCLUDE_DIR/LIB_DIR were given, but no usable jansson.h >= $PKG_MIN_VERSION there" >&2
    exit 1
  fi
  use_system=yes
else
  # no `command -v` guard: checkbashisms flags it, and simply running
  # pkg-config gives the same answer (127 when it is not installed)
  if pkg-config --atleast-version="$PKG_MIN_VERSION" "$PKG_CONFIG_NAME" 2>/dev/null; then
    PKG_CFLAGS=`pkg-config --cflags "$PKG_CONFIG_NAME"`
    PKG_LIBS=`pkg-config --libs "$PKG_CONFIG_NAME"`
    probe "$PKG_CFLAGS" && use_system=yes
  fi
  if [ "$use_system" = no ] && probe ""; then
    # no (usable) pkg-config entry, but the header is on the default
    # search path with the floor satisfied: bare -ljansson
    PKG_CFLAGS=""
    PKG_LIBS="-ljansson"
    use_system=yes
  fi
fi

if [ "$use_system" = yes ]; then
  echo "using system libjansson (>= $PKG_MIN_VERSION)"
  VENDOR_OBJS=""
else
  if [ -z "$JANSSONR_VENDOR" ]; then
    echo "no system libjansson >= $PKG_MIN_VERSION found; compiling the bundled Jansson 2.15.1"
    echo "  (install libjansson-dev (deb) / jansson-devel (rpm) / jansson (brew)"
    echo "   before installing janssonr to link the system library instead)"
  fi
  PKG_CFLAGS="-Iconfig-unix -Ijansson -DHAVE_CONFIG_H"
  PKG_LIBS=""
  VENDOR_OBJS='$(JANSSON_OBJS)'
fi

sed -e "s|@cflags@|$PKG_CFLAGS|" -e "s|@libs@|$PKG_LIBS|" \
    -e "s|@vendor_objs@|$VENDOR_OBJS|" src/Makevars.in > src/Makevars
exit 0
