#!/usr/bin/env bash

# WARNING -- if you add a package here, also add it to
# the gap_reset_workspace() command in 
#    <SAGE_ROOT>/src/sage/interfaces/gap.py
#

if [ -z "$SAGE_LOCAL" ]; then 
    echo >&2 "SAGE_LOCAL undefined ... exiting" 
    echo >&2 "Maybe run 'sage --sh'?" 
    exit 1 
fi 

GAP_DIR="$SAGE_LOCAL/gap/latest"
PKG_DIR="$GAP_DIR/pkg"

# Some GAP packages have weird permissions which can prevent us from
# overwriting them
chmod -R u+rwX "$PKG_DIR" || mkdir -p "$PKG_DIR"

$CP -p SPKG.txt "$PKG_DIR"
if [ $? -ne 0 ]; then
    echo >&2 "Error copying SPKG.txt"
    exit 1
fi


cd src/

# Apply fixes to upstream source
echo "Applying patches..."
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done


for p in \
    aclib crime ctbllib cryst crystcat design factint grape \
    guava-3.13 Hap1.11 HAPcryst happrime laguna polymaking \
    sonata toric1.8 polycyclic-2.11 autpgrp Alnuth-3.0.0 atlasrep
do
    echo "Copying package $p"
    $CP -pr $p "$PKG_DIR"
    if [ $? -ne 0 ]; then
        echo >&2 "Error copying package $p."
        exit 1
    fi
done


# Build GRAPE package
cd "$PKG_DIR/grape"
rm -rf bin   # added since rebuilding breaks otherwise
./configure "$GAP_DIR"
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring GRAPE package."
    exit 1
fi
$MAKE -j1
if [ $? -ne 0 ]; then
    echo >&2 "Error building GRAPE package."
    exit 1
fi


# Build GUAVA package
cd "$PKG_DIR"/guava-3* && ./configure "$GAP_DIR"
if [ $? -ne 0 ]; then 
    echo >&2 "Error configuring GUAVA packagae."
    exit 1
fi
$MAKE -j1
if [ $? -ne 0 ]; then 
    echo >&2 "Error building GUAVA package."
    exit 1
fi

# Some GAP packages have weird permissions
chmod -R u+rwX "$PKG_DIR"

touch "$SAGE_LOCAL/bin/gap_stamp"

