# 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 SPKG.txt "$PKG_DIR"
if [ $? -ne 0 ]; then
    echo >&2 "Error copying SPKG.txt"
    exit 1
fi


cd src/

for p in \
    aclib cohomolo-1.6.4 corelg crime ctbllib cryst crystcat design factint gbnp grape \
    guava-3.13 Hap1.11 HAPcryst happrime hecke laguna liealgdb liepring liering loops mapclass nq-2.5.3 polymaking \
    QPA-1.25 quagroup repsn sla sonata toric1.8 polycyclic-2.11 autpgrp Alnuth-3.0.0 atlasrep
do
    echo "Copying package $p"
    cp -r $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


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

# Build nq package
cd "$PKG_DIR/nq-2.5.3"
./configure --with-gaproot="$GAP_DIR"
if [ $? -ne 0 ]; then
    echo >&2 "Error configuring nq package."
    exit 1
fi
$MAKE 
if [ $? -ne 0 ]; then
    echo >&2 "Error building nq package."
    exit 1
fi


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


