# Ask GAP for the directory where sysinfo.gap lives. This is to
# support system GAP installations. This root-path gathering
# command is borrowed from gap's spkg-configure.m4 and modified
# to separate the paths with spaces.
GAPRUN="gap -r -q --bare --nointeract -c"
_cmd='Display(JoinStringsWithSeparator(GAPInfo.RootPaths," "));'
GAP_ROOT_PATHS=$(${GAPRUN} "${_cmd}")

# Loop though GAP_ROOT_PATHS looking for sysinfo.gap
GAP_ROOT=""
for grp in $GAP_ROOT_PATHS; do
    if [ -f "${grp}/sysinfo.gap" ]; then
        GAP_ROOT=$grp
        echo "found GAP root $GAP_ROOT"
        break
    fi
done

# Try the old sage default if nothing else worked.
if [ -z "$GAP_ROOT" ]; then
    GAP_ROOT="$SAGE_LOCAL/lib/gap"
    echo "falling back to GAP root $GAP_ROOT"
fi

# And finally, throw an error ASAP if the build is going to fail anyway.
if [ ! -f "${GAP_ROOT}/sysinfo.gap" ]; then
    sdh_die "no sysinfo.gap in your gap root"
fi

# Where to install these packages
PKG_DIR="$SAGE_LOCAL/lib/gap/pkg"

PKG_SRC_DIR="$(pwd)/src/pkg"
cd "$PKG_SRC_DIR"

# directly install pure GAP packages
#

sdh_install \
    uuid \
    jupyterkernel \
    jupyterviz \
    "$PKG_DIR"

install_compiled_pkg()
{
    local pkg="$1"
    # Install the bin/ dir (where compiled modules should end up)
    # under <prefix>/lib/gap; we then symlink to it later
    sdh_install * "$SAGE_LOCAL/lib/gap/pkg/$pkg"

    # TODO:
    # Clean up any build artifacts before installing the rest of the package
    # Also remove configure/Makefiles
    # Note: None, if any of the packages really have a proper install target
    #make clean  # Works for some packages but not all
    #rm -rf bin/
    #rm -rf configure configure.* config.* autogen.sh *.m4 Makefile* m4/

}

# Build and install compiled packages:
#
# These packages have an old ./configure that take the GAP_ROOT as a positional
# argument
for pkg in json
do
    echo "Building GAP package $pkg"
    CFLAGS="$CFLAGS -Wno-implicit-function-declaration"
    export CFLAGS
    cd "$PKG_SRC_DIR/$pkg"
    ./configure "$GAP_ROOT"
    sdh_make
    install_compiled_pkg "$pkg"
    cd "$PKG_SRC_DIR"
done

# These packages have a new-style autoconf ./configure
# that takes --with-gaproot

#############################################################################
########## add extra parameters for packages' configures here ###############
#
pararr=( " " )
##############################################################################

parind=0
for pkg in zeromqinterface
do
    echo "Building GAP package $pkg"
    cd "$PKG_SRC_DIR/$pkg"
    sdh_configure --with-gaproot="$GAP_ROOT" ${pararr[$parind]}
    ((parind+=1))
    sdh_make
    install_compiled_pkg "$pkg"
    cd "$PKG_SRC_DIR"
done
