#!/usr/bin/env bash

# Installation script for gap3; based on the installation script for gap4.

###########################################
## SETUP
###########################################

PACKAGE_SHORTNAME=gap3
VERSION=`cat package-version.txt`
GAP3_DIR="gap-$VERSION"
INSTALL_DIR="$SAGE_LOCAL/$PACKAGE_SHORTNAME/$GAP3_DIR"

echo "spkg-install is using"
echo "VERSION = $VERSION"
echo "GAP3_DIR = $GAP3_DIR"
echo "INSTALL_DIR = $INSTALL_DIR"

###########################################
## MODIFY UPSTREAM
###########################################

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

###########################################
## INSTALLATION
###########################################

cd gap3/src
$MAKE
if [ $? -ne 0 ]; then
    echo >&2 "Error building $PACKAGE_SHORTNAME."
    exit 1
fi
cd ../..

echo "Installing (copying) files..."
mkdir -p "$INSTALL_DIR" &&
cp -rf * "$INSTALL_DIR"
if [[ $? -ne 0 ]]; then
    echo >&2 "Error copying $PACKAGE_SHORTNAME files."
    exit 1
fi

echo "Creating symlink to new $PACKAGE_SHORTNAME installation..."
rm -f "$SAGE_LOCAL/$PACKAGE_SHORTNAME/latest"
ln -s "$GAP3_DIR" "$SAGE_LOCAL/$PACKAGE_SHORTNAME/latest"

echo "Copying GAP3 startup script..."
rm -f "$SAGE_LOCAL/bin/gap3"
cp gap3/bin/gap.sh "$SAGE_LOCAL/bin/gap3"
if [[ $? -ne 0 ]]; then
    echo >&2 "Error copying customized $PACKAGE_SHORTNAME startup script."
    exit 1
fi
