#!/usr/bin/env bash

set -e

[ -n "${SAGE_ROOT}" ] || SAGE_ROOT="$(pwd)/../../../"


# determine latest version.
GIT_VERSION="$(curl http://docs.mathjax.org/en/latest/installation.html | grep 'Current Version' | sed 's|^.*archive/||g' | sed 's/.zip".*//g')"
echo "GIT_VERSION=$GIT_VERSION"

# fetch and rename latest version.
URL="https://github.com/mathjax/MathJax/archive/${GIT_VERSION}.zip"
echo "Downloading $URL"
rm -rf src
if [ -z "$UPSTREAM_SOURCE_TARBALL" ]; then
    tar xzf <( curl -L "$URL" )
else
    tar xzf "$UPSTREAM_SOURCE_TARBALL"
fi
mv MathJax-${GIT_VERSION} src

# Strip mathjax according to
# https://github.com/mathjax/MathJax-docs/wiki/Guide%3A-reducing-size-of-a-mathjax-installation

# Trimming I -- removing files unnecessary for deployment
FILEDIRS_TO_REMOVE='docs/ test/ unpacked/ .gitignore README-branch.txt README.md bower.json'
for filedir in ${FILEDIRS_TO_REMOVE} ; do
    rm -rf "src/${filedir}"
done

# Trimming II -- not strictly necessary (requires the patch nopng_config.patch)
rm -rf 'src/fonts/HTML-CSS/TeX/png/'

# Trimming III -- fonts
FONTS_TO_REMOVE='Asana-Math Gyre-Pagella Gyre-Termes Latin-Modern Neo-Euler'
for font in ${FONTS_TO_REMOVE} ; do
    find . -type d -name "${font}" -prune -exec rm -rf {} \;
done

FONT_FORMATS_TO_REMOVE='eot otf svg'
for fontformat in ${FONT_FORMATS_TO_REMOVE} ; do
    find . -type d -name "${fontformat}" -prune -exec rm -rf {} \;
done

# Trimming IV -- reducing input and output options
OUTPUT_OPTIONS_TO_REMOVE='NativeMML SVG'
for output in ${OUTPUT_OPTIONS_TO_REMOVE} ; do
    rm -rf "src/jax/output/${output}"
done

# repack
tar czf "$SAGE_ROOT/upstream/mathjax-${GIT_VERSION}.tar.gz" src
rm -rf src

# update package info
echo "${GIT_VERSION}" > 'package-version.txt'
"$SAGE_ROOT"/sage --package fix-checksum mathjax


