#!/usr/bin/env sh

ROOT=$(
    cd "$(dirname "$0")" || exit
    pwd
)

SRC="${ROOT}/src"
SE2="${SRC}/se2"
IGRAPH="${SE2}/vendor/igraph"
REL_IGRAPH=".${IGRAPH#"$SRC"}"

# Only collects C files. If C++ needed, extend patterns.
collect_objs() {
    cd "$SRC" || exit
    obj_path="${1#"$SRC"}"
    find ".$obj_path" -name '*.c' | sed -n 's/\.c/.o/p' | tr '\n' ' '
}

# Attempt to piece-wise collect igraph source files to reduce hard to handle
# dependencies.
SE2_OBJS=$(collect_objs "${SE2}/src")

IGRAPH_OBJS="${REL_IGRAPH}/src/core/interruption.o \
    ${REL_IGRAPH}/src/core/vector.o \
    ${REL_IGRAPH}/src/core/memory.o \
    ${REL_IGRAPH}/src/core/indheap.o \
    ${REL_IGRAPH}/src/core/matrix.o \
    ${REL_IGRAPH}/src/core/vector_ptr.o \
    ${REL_IGRAPH}/src/core/vector_list.o \
    ${REL_IGRAPH}/src/core/printing.o \
    ${REL_IGRAPH}/src/core/error.o \
    ${REL_IGRAPH}/src/core/sparsemat.o \
    ${REL_IGRAPH}/src/graph/type_indexededgelist.o \
    ${REL_IGRAPH}/src/graph/iterators.o \
    ${REL_IGRAPH}/src/graph/type_common.o \
    ${REL_IGRAPH}/src/graph/caching.o \
    ${REL_IGRAPH}/src/graph/attributes.o \
    ${REL_IGRAPH}/src/internal/hacks.o \
    ${REL_IGRAPH}/src/internal/qsort.o \
    ${REL_IGRAPH}/src/internal/qsort_r.o \
    ${REL_IGRAPH}/src/math/complex.o \
    ${REL_IGRAPH}/src/math/utils.o \
    ${REL_IGRAPH}/src/properties/degrees.o \
    ${REL_IGRAPH}/src/constructors/basic_constructors.o \
    ${REL_IGRAPH}/src/community/community_misc.o \
    ${REL_IGRAPH}/src/linalg/arpack.o"

IGRAPH_RAND_OBJS=$(collect_objs "${IGRAPH}/src/random")
CS_OBJS=$(collect_objs "${IGRAPH}/vendor/cs")
PCG_OBJS=$(collect_objs "${IGRAPH}/vendor/pcg")
LINALG_OBJS=$(collect_objs "${IGRAPH}/vendor/lapack")
F2C_OBJS=$(collect_objs "${SRC}/f2c")

cat <<_EOF_ >"${ROOT}/src/Makevars"
# Generated by configure; do not edit.
PKG_CFLAGS = \$(C_VISIBILITY)
PKG_CPPFLAGS = -pthread -DUSING_R -DSE2PAR -I${ROOT}/src/include -I${SE2}/include -I${IGRAPH}/include -I${IGRAPH}/vendor -I${IGRAPH}/src
PKG_LIBS = -pthread -lm
OBJECTS = speakeasyR.o ${SE2_OBJS} ${IGRAPH_OBJS} ${IGRAPH_RAND_OBJS} ${CS_OBJS} ${PCG_OBJS} ${LINALG_OBJS} ${F2C_OBJS}
_EOF_
