#!/usr/bin/env bash

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

touch "$SAGE_LOCAL/bin/gap_stamp"

GAP=`echo 'Print(Concatenation("gap-", GAPInfo.Version));' | gap -q`
if [ -z "$GAP" ]; then
    echo >&2 "Error determining the version of GAP installed in Sage."
    exit 1
fi
# GAP should now be set to installed gap version - eg, GAP=gap-4.4.12

echo "********************************************************************"
echo "Installing optional GAP databases, which may not be open source."
echo "Installing GAP packages to $SAGE_LOCAL/lib/$GAP/..."
echo "Please see SPKG.txt for license details."
echo "********************************************************************"

cd src/

rm -rf "$SAGE_LOCAL/gap/latest/small"
cp -rp small "$SAGE_LOCAL/gap/latest/"
if [ $? -ne 0 ]; then
    echo >&2 "Error installing small group database."
    exit 1
fi 
echo "Installed small group database."

rm -rf "$SAGE_LOCAL/gap/latest/prim"
cp -rp prim "$SAGE_LOCAL/gap/latest/"
if [ $? -ne 0 ]; then
    echo >&2 "Error installing prim database."
    exit 1
fi 
echo "Installed prim database."

rm -rf "$SAGE_LOCAL/gap/latest/trans"
cp -rp trans "$SAGE_LOCAL/gap/latest/"
if [ $? -ne 0 ]; then
    echo >&2 "Error installing trans database."
    exit 1
fi 
echo "Installed trans database."

rm -rf "$SAGE_LOCAL/gap/latest/pkg/tomlib"
cp -rp pkg/tomlib "$SAGE_LOCAL/gap/latest/pkg/"
if [ $? -ne 0 ]; then
    echo >&2 "Error installing tomlib database."
    exit 1
fi 
echo "Installed tomlib database."

sage -c "gap_reset_workspace()"

