#!/usr/bin/env bash -x
#
# Script to prepare a GIAC spkg for Sage.  This script is only for the
# package maintainer, not for building GIAC during a Sage install.
#

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

# Exit on failure
set -e

VERSION="1.9.0"
VERSIONREV="15"
PATCHSUFFIX="p0"

# The upstream tarball name is: giac"$SOURCEORIG".tar.gz
SOURCEORIG=_"$VERSION"-"$VERSIONREV"

# The name of the output file without tar.gz or tar.bz2 extension
OUTPUTFILEBASENAME="$SAGE_DISTFILES"/giac-"$VERSION"."$VERSIONREV""$PATCHSUFFIX"

# Testing if the output file already exist in one of gz or bz2 format:
if [ -f "$OUTPUTFILEBASENAME".tar.gz -o -f "$OUTPUTFILEBASENAME".tar.bz2 ] ; then
    echo >&2 "there is already a giac archive of this version"
    exit 1
fi

# Build a temporary working dir. (preferably, a subdir of SAGE_DISTFILES)
TARGET=$(mktemp -d -p"$SAGE_DISTFILES" 2>/dev/null || mktemp -d)
echo "Working in $TARGET"
ORIGDIR=`pwd`
cd "$TARGET"

# Downloading upstream source
sage-download-file "http://www-fourier.ujf-grenoble.fr/~parisse/debian/dists/stable/main/source/giac$SOURCEORIG.tar.gz" "giac$SOURCEORIG.tar.gz"


# untar upstream source
tar -xzf giac"$SOURCEORIG".tar.gz


# rename top sourcedir
mv giac-"$VERSION" src

# remove unnecessary files
rm -rf src/doc/pari/*.html

rm -f src/doc/*.wasm src/doc/*.js
sed -E -i.bak '/XCASHTML/s/[^ ]*[.](wasm|js)//g' src/doc/Makefile.am

# removing french html doc, but keep keywords, and working makefiles.
# NB: the french html doc is huge and not GPL.
# it is freely redistributable only for non commercial purposes.
cd src/doc/fr
rm -rf [^Mkx]*
rm -rf *.pdf *.eps *.pdf *.png *.cxx *.cas *.jpg *.tex *.stamp *html* cas* *.fig fig*
# repair the build procedure with a minimal Makefile.am
echo -e "EXTRA_DIST = xcasmenu xcasex keywords\n\nlocaldocdir = \$(docdir)/fr \n\n\
dist_localdoc_DATA = xcasmenu xcasex keywords html_mall html_mtt html_vall">Makefile.am
# copy and adjust a minimal Makefile.in
cp ../local/Makefile.in ./
sed -ie 's|localdocdir = $(docdir)/local|localdocdir = $(docdir)/fr|' Makefile.in
sed -ie 's|doc/local|subdir = doc/fr|g' Makefile.in
#
touch html_mall
touch html_mtt
touch html_vall
#

# building giac source tarball for the spkg
cd ../../

# get rid of micropython
rm -rf micropython*
sed -i.bak 's/micropython-[^ ]*//' Makefile.am configure.ac

for a in "$SAGE_ROOT"/build/pkgs/giac/patches/autotools/*.patch; do
    patch -p1 < $a
done
autoreconf -fi

cd ..
tar -cjf "$OUTPUTFILEBASENAME".tar.bz2 src

# cleaning extracted dir.
cd ..
### rm -rf "$TARGET"

# going back to starting dir
cd "$ORIGDIR"
#$SAGE_ROOT/sage -package update giac "$VERSION"."$VERSIONREV""$PATCHSUFFIX"
echo "$VERSION"."$VERSIONREV""$PATCHSUFFIX" > build/pkgs/giac/package-version.txt
$SAGE_ROOT/sage -package fix-checksum giac
