GAP_ROOT="$SAGE_LOCAL/share/gap"
PKG_DIR="$GAP_ROOT/pkg"

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

# directly install pure GAP packages
#
#    happrime - no longer distributed, partly merged in Hap,
#    cf. https://www.gap-system.org/Packages/packages.html#deppkg
#    (GAP 4.8.6 still had it, but this is gone in 4.10)

sdh_install \
    aclib-* \
    AutoDoc-* \
    corelg \
    crime-* \
    cryst \
    crystcat \
    design \
    gbnp \
    Hap* \
    HAPcryst \
    hecke-* \
    liealgdb-* \
    liepring-* \
    liering \
    loops \
    MapClass-* \
    polymaking \
    qpa-* \
    quagroup \
    radiroot-* \
    repsn \
    sla \
    sonata-* \
    Toric-* \
    utils-* \
    "$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 bin/ "$SAGE_LOCAL/lib/gap/pkg/$pkg"

    # Clean up any build artificts 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/

    # Create the bin/ symlink
    ln -s "$SAGE_LOCAL/lib/gap/pkg/$pkg/bin" bin

    # Install the rest of the package files
    sdh_install * "$PKG_DIR/$pkg"
}

# Build and install compiled packages:
#
# These packages have an old ./configure that take the GAP_ROOT as a positional
# argument
for pkg in cohomolo-* grape-* guava-*
do
    echo "Building GAP package $pkg"
    cd "$PKG_SRC_DIR/$pkg"
    ./configure "$GAP_ROOT"
    sdh_make -j1
    install_compiled_pkg "$pkg"
    cd "$PKG_SRC_DIR"
done

# These packages (currently just one) have a new-style autoconf ./configure
# that takes --with-gaproot
for pkg in nq-*
do
    cd "$PKG_SRC_DIR/$pkg"
    sdh_configure --with-gaproot="$GAP_ROOT"
    sdh_make -j1
    install_compiled_pkg "$pkg"
    cd "$PKG_SRC_DIR"
done
