#!/usr/bin/env bash
#
# Script to prepare a GAP3 tarball for Sage from the semi-official
# version on Jean Michel's website.
#
# This script is only for the package maintainer,
# not for building GAP3 during a Sage install.
#
# WARNING: This script will delete/overwrite files in this directory
# and its subdirectories!
#
# HOW TO MAKE THE TARBALL:
# 1) sage --sh build/pkgs/gap3/spkg-src
#
# needs sage in your PATH.
#
# AUTHOR: Christian Stump (Jun 2017)

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

PACKAGENAME="gap3"
DOWNLOADVERSION="$PACKAGENAME-jm"
TARSOURCE=`wget -O - -o /dev/null  https://webusers.imj-prg.fr/~jean.michel/gap3/ | grep -o -m 1 'href=".*"' | awk '{print substr($0,7,length($0)-7) }'`
UPLOADVERSION=`echo $TARSOURCE | awk '{print substr($0,8,length($0)-14) }'`

cd build/pkgs/$PACKAGENAME

TARTARGET="$SAGE_DISTFILES/$PACKAGENAME-$UPLOADVERSION.tar.gz"

echo "### Remove old gap3 folder and tarball    ###"
rm -f $TARSOURCE
rm -rf $DOWNLOADVERSION

echo "### Download and extract upstream tarball ###"
wget --no-check-certificate https://webusers.imj-prg.fr/~jean.michel/$PACKAGENAME/$TARSOURCE
echo "### Untar'ing the upstream tarball        ###"
tar -zxf $TARSOURCE
echo "### Remove downloaded tarball             ###"
rm -f $TARSOURCE

echo "### Moving the files to its place $PACKAGENAME    ###"
mv $DOWNLOADVERSION $PACKAGENAME
cd $PACKAGENAME

echo "### Removing the package binaries         ###"
cd pkg
make cleanpackages
cd ..
echo "### Removing all bin binaries             ###"
cd bin
grep -r -m 1 "^"  . | grep "^Binary file" | xargs rm -f
cd ..

echo "### replacing lib/init.g, bin/gap.sh,     ###"
echo "### src/Makefile by the sage versions     ###"
mv -f sage/init.g lib/init.g
mv -f sage/gap.sh bin/gap.sh
mv -f sage/Makefile src/Makefile
chmod a+x bin/gap.sh
rm -f sage/*
rmdir sage

cd ..

echo "### Tar'ing the archive to $TARTARGET     ###"
tar -czf $TARTARGET $PACKAGENAME

echo "### Updating package-version.txt          ###"
echo $UPLOADVERSION > 'package-version.txt'

echo "### Fixing the checksum                   ###"
../../../sage --package fix-checksum "$PACKAGENAME"

echo "### Removing untar'ed archive             ###"
rm -rf $PACKAGENAME
