#!/bin/bash

set -euo pipefail

# set paths to use
python_path=$1
temp_dir=$2
finalize_script=$3
report_to=$4

echo "Running with the following parameters:"
echo "Python path: $python_path"
echo "Correction temp dir: $temp_dir"
echo "finalize script: $finalize_script"
echo "job ID: ${SLURM_JOB_ID:-none}"

# set-up enviroment
source /etc/profile.d/modules.sh
module load texlive/2019

# make sure we use agg backend
export MPLBACKEND=AGG

# Ensure Python uses UTF-8 for files by default
export LANG=en_US.UTF-8

if [ -n "$report_to" ]; then
    shopt -s failglob  # Fail fast if there are no notebooks found
    echo "Converting notebooks"
    ${python_path} -m nbconvert --to rst --TemplateExporter.exclude_input=True "$temp_dir"/*.ipynb
    shopt -u failglob  # Restore default glob behaviour
fi

${python_path} "$finalize_script"