#!/bin/sh
# configure -- macOS / Linux configuration for the rvtk R package.
# Detects a system-installed VTK (>= 9.1.0) via Homebrew (macOS) or common
# system prefixes, then writes inst/vtk.conf so that rvtk::CppFlags() and
# rvtk::LdFlags() return the correct flags for downstream packages.

set -e

VTK_MIN_VERSION="9.1.0"
VTK_MIN_SUFFIX="$(echo "${VTK_MIN_VERSION}" | sed 's/\([0-9]*\)\.\([0-9]*\)\..*/\1.\2/')"

# ---------------------------------------------------------------------------
# Shared detection helpers (vtk_detect_from_prefix + state variables)
# ---------------------------------------------------------------------------
. tools/vtk-detect.sh

# ---------------------------------------------------------------------------
# Unix-specific build-flag helper
# ---------------------------------------------------------------------------

## vtk_build_flags LIB_PREFIX [RPATH]
## Populates vtk_cppflags and vtk_libs using vtk_version_suffix / vtk_include_dir.
vtk_build_flags() {
    _lib="$1"
    _rpath="${2:-}"
    if test -n "${vtk_version_suffix}"; then
        _s="-${vtk_version_suffix}"
    else
        _s=""
    fi
    vtk_cppflags="-isystem${vtk_include_dir}"
    vtk_libs="-L${_lib}/lib"
    vtk_libs="${vtk_libs} -lvtkIOLegacy${_s}"
    vtk_libs="${vtk_libs} -lvtkIOXML${_s}"
    vtk_libs="${vtk_libs} -lvtkIOXMLParser${_s}"
    vtk_libs="${vtk_libs} -lvtkIOCore${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonCore${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonDataModel${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonExecutionModel${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonMath${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonMisc${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonSystem${_s}"
    vtk_libs="${vtk_libs} -lvtkCommonTransforms${_s}"
    vtk_libs="${vtk_libs} -lvtksys${_s}"
    if test -n "${_rpath}"; then
        vtk_libs="${vtk_libs} -Wl,-rpath,${_rpath}"
    fi
}

# ---------------------------------------------------------------------------
# 0. User-supplied VTK_DIR (highest priority)
# ---------------------------------------------------------------------------
if test -n "${VTK_DIR}"; then
    echo "Checking VTK_DIR=${VTK_DIR} ..."
    if vtk_detect_from_prefix "${VTK_DIR}"; then
        vtk_build_flags "${VTK_DIR}" "${VTK_DIR}/lib"
        vtk_found="yes"
        echo "  -> found VTK${vtk_version_suffix:+- }${vtk_version_suffix}"
    else
        echo "  -> VTK_DIR does not satisfy >= ${VTK_MIN_VERSION}; trying automatic detection."
    fi
fi

# ---------------------------------------------------------------------------
# 1. macOS: Homebrew
# ---------------------------------------------------------------------------
os_type="$(uname -s)"
if test "${vtk_found}" = "no" && test "${os_type}" = "Darwin"; then
    if command -v brew > /dev/null 2>&1; then
        if brew --prefix vtk > /dev/null 2>&1; then
            _brew_pfx="$(brew --prefix vtk)"
            echo "Checking Homebrew VTK at ${_brew_pfx} ..."
            if vtk_detect_from_prefix "${_brew_pfx}"; then
                vtk_build_flags "${_brew_pfx}"
                vtk_found="yes"
                echo "  -> found VTK${vtk_version_suffix:+- }${vtk_version_suffix}"
            else
                echo "  -> Homebrew VTK is too old (< ${VTK_MIN_VERSION})."
            fi
        fi
    fi
fi

# ---------------------------------------------------------------------------
# 2. pkg-config
# ---------------------------------------------------------------------------
if test "${vtk_found}" = "no"; then
    if command -v pkg-config > /dev/null 2>&1; then
        vtk_pc=""
        for _n in vtk vtk-9.5 vtk-9.4 vtk-9.3 vtk-9.2 vtk-9.1 vtk9 VTK; do
            if pkg-config --exists "${_n}" 2>/dev/null; then
                vtk_pc="${_n}"; break
            fi
        done
        if test -n "${vtk_pc}"; then
            echo "Checking pkg-config name '${vtk_pc}' ..."
            if pkg-config --atleast-version="${VTK_MIN_VERSION}" "${vtk_pc}"; then
                vtk_cppflags="$(pkg-config --cflags "${vtk_pc}" | sed 's/-I/-isystem/g')"
                vtk_libs="$(pkg-config --libs "${vtk_pc}")"
                vtk_version="$(pkg-config --modversion "${vtk_pc}")"
                vtk_found="yes"
                echo "  -> found VTK ${vtk_version} via pkg-config"
            else
                echo "  -> pkg-config VTK is too old (< ${VTK_MIN_VERSION})."
            fi
        fi
    fi
fi

# ---------------------------------------------------------------------------
# 3. Linux: well-known system prefixes
# ---------------------------------------------------------------------------
if test "${vtk_found}" = "no" && test "${os_type}" = "Linux"; then
    for _base in /usr /usr/local; do
        if vtk_detect_from_prefix "${_base}"; then
            vtk_build_flags "${_base}" "${_base}/lib"
            vtk_found="yes"
            echo "Found VTK at ${_base}"
            break
        fi
    done
fi

# ---------------------------------------------------------------------------
# 4. Fallback: download pre-built static libraries from GitHub releases
# ---------------------------------------------------------------------------
VTK_PREBUILT_VERSION="9.5.2"
VTK_PREBUILT_BASE_URL="https://github.com/astamm/rvtk/releases/download/v${VTK_PREBUILT_VERSION}"

if test "${vtk_found}" = "no"; then
    echo "No system VTK found. Trying pre-built static libraries from GitHub..."

    # Determine archive name from OS + arch
    _arch="$(uname -m)"
    _tarball=""
    case "${os_type}" in
        Darwin)
            case "${_arch}" in
                arm64)  _tarball="vtk-${VTK_PREBUILT_VERSION}-darwin-arm64.tar.gz" ;;
                x86_64) _tarball="vtk-${VTK_PREBUILT_VERSION}-darwin-x86_64.tar.gz" ;;
                *)
                    echo "ERROR: Unsupported macOS architecture '${_arch}'." >&2
                    exit 1 ;;
            esac ;;
        Linux)
            case "${_arch}" in
                x86_64) _tarball="vtk-${VTK_PREBUILT_VERSION}-linux-x86_64.tar.gz" ;;
                *)
                    echo "ERROR: Unsupported Linux architecture '${_arch}'." >&2
                    exit 1 ;;
            esac ;;
        *)
            echo "ERROR: Cannot find VTK >= ${VTK_MIN_VERSION} and no pre-built" >&2
            echo "       archive is available for OS '${os_type}'." >&2
            exit 1 ;;
    esac

    _url="${VTK_PREBUILT_BASE_URL}/${_tarball}"

    # Extract into inst/prebuilt/ so that headers and static libs become part
    # of the installed package.  Storing absolute $(pwd)-relative paths in
    # vtk.conf is unsafe: R CMD build creates a tarball in a temp directory,
    # so $(pwd) at configure time would be deleted after installation.
    _prebuilt_dir="inst/prebuilt"

    echo "  Downloading ${_url} ..."
    mkdir -p "${_prebuilt_dir}"
    _tmp="$(mktemp /tmp/vtk-prebuilt.XXXXXX.tar.gz)"

    if command -v curl > /dev/null 2>&1; then
        curl -fsSL "${_url}" -o "${_tmp}" || {
            echo "ERROR: Failed to download pre-built VTK from ${_url}" >&2; exit 1
        }
    elif command -v wget > /dev/null 2>&1; then
        wget -q "${_url}" -O "${_tmp}" || {
            echo "ERROR: Failed to download pre-built VTK from ${_url}" >&2; exit 1
        }
    else
        echo "ERROR: Neither curl nor wget is available to download pre-built VTK." >&2
        exit 1
    fi

    tar -xzf "${_tmp}" -C "${_prebuilt_dir}" --strip-components=1
    rm -f "${_tmp}"
    echo "  Extracted to ${_prebuilt_dir}"

    if vtk_detect_from_prefix "${_prebuilt_dir}"; then
        vtk_version="${VTK_PREBUILT_VERSION}"
        if test -n "${vtk_version_suffix}"; then
            _sfx="-${vtk_version_suffix}"
        else
            _sfx=""
        fi
        echo "  -> using pre-built VTK ${VTK_PREBUILT_VERSION}"

        # Write symbolic vtk.conf.  Actual include/lib paths are resolved at
        # runtime by rvtk::read_vtk_conf() via system.file("prebuilt", ...).
        mkdir -p inst
        cat > inst/vtk.conf << CONF
VTK_VERSION=${vtk_version}
VTK_SUFFIX=${_sfx}
VTK_PREBUILT=yes
CONF
        echo "Written inst/vtk.conf (pre-built; paths resolved at runtime)"
        echo "  VTK_VERSION=${vtk_version}"
        echo "  VTK_SUFFIX=${_sfx}"
        exit 0
    else
        echo "ERROR: Pre-built VTK archive layout not recognised at ${_prebuilt_dir}" >&2
        exit 1
    fi
fi

## Determine version string if not already set (from pkg-config path).
if test -z "${vtk_version}"; then
    if test -n "${vtk_version_suffix}"; then
        vtk_version="${vtk_version_suffix}.0"
    else
        vtk_version="unknown"
    fi
fi

# ---------------------------------------------------------------------------
# Write inst/vtk.conf
# ---------------------------------------------------------------------------
mkdir -p inst
cat > inst/vtk.conf << EOF
VTK_VERSION=${vtk_version}
VTK_CPPFLAGS=${vtk_cppflags}
VTK_LIBS=${vtk_libs}
VTK_INCLUDE_DIR=${vtk_include_dir}
EOF

echo "Written inst/vtk.conf"
echo "  VTK_VERSION=${vtk_version}"
echo "  VTK_CPPFLAGS=${vtk_cppflags}"
echo "  VTK_LIBS=${vtk_libs}"
