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 \
    genss-* \
    Hap* \
    HAPcryst \
    hecke-* \
    liealgdb-* \
    liepring-* \
    liering-* \
    loops-* \
    MapClass-* \
    PackageManager-* \
    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-* crypting-* grape-* guava-* orb-*
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 have a new-style autoconf ./configure
# that takes --with-gaproot

#############################################################################
########## add extra parameters for packages' configures here ###############
#
# ng         : none
# io         : none
# semigroups needs to use external libsemigroups
# digraphs   needs to use external planarity
pararr=( " " " " "--with-external-planarity" "--with-external-libsemigroups" )
##############################################################################

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