#!/usr/bin/env bash

#This is to convert to html the notebooks with embedded LaTeX structures
#as used in the latex_envs extension
#required: nodejs, perl

listOfFiles=$*
#from http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in
SDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )  #this should be the conversion directory

stillIPython3=false
nbextensionsDIR=~/.local/share/jupyter/nbextensions
jup_exe=jupyter

if $stillIPython3
then
	nbextensionsDIR=~/.ipython/nbextensions
	jup_exe=ipython3
fi

if [ ! -f ./thmsInNb.tpl ]
then
    cp -n $SDIR/thmsInNb.tpl .  # for conversion, the template file must be in the same directory (or in templates/html dir)
    thmsInNbCopied=true
fi


for f in $listOfFiles
do
  echo [Translating... $f ]
  cp $f temp.ipynb
  perl -pi -e s/'\\\\\['/'\$\$'/ temp.ipynb
  perl -pi -e s/'\\\\\]'/'\$\$'/ temp.ipynb
  $jup_exe nbconvert --template=thmsInNb --to html  temp --output temp
  echo [Post Html processing]
  nodejs $SDIR/post_html_thms.js < temp.html > ${f%.ipynb}.html
  #echo [Updating links]
  #perl -pi -e s/.ipynb/.html/g ${f%.ipynb}.html
  echo Done
done
cp -n $nbextensionsDIR/latex_envs/latex_envs.css . # copy the css file in the same directory as the html
if $thmsInNbCopied
  then rm thmsInNb.tpl #cleaning
fi
rm temp.*
