#!/usr/bin/env bash

set -e

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

# determine the latest version
GIT_VERSION="$(curl https://github.com/mathjax/MathJax/releases | grep  'MathJax v' | head -1 | sed 's|^.*MathJax v||g' | sed 's/\s*$//g')"
echo "GIT_VERSION=$GIT_VERSION"

# fetch and rename the latest version
URL="https://github.com/mathjax/MathJax/archive/refs/tags/${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

# put files under mathjax directory
mkdir src
mv MathJax-${GIT_VERSION}/es5 src/mathjax
rm -r MathJax-${GIT_VERSION}

PACKAGE_VERSION=${GIT_VERSION}

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

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