#!/bin/bash

# set paths to use
nb_path=$1
python_path=$2
ipython_path=$3
jupyter_path=$4
ipcluster_path="${5}"
activate_path=$6
uuid=$7
notebook=$8
detector=$9
caltype=${10}
final=${11}
finalize=${12}
cluster_cores=${13}

echo "Running with the following parameters:"
echo "Notebook path: $nb_path"
echo "Python path: $python_path"
echo "IPython path: $ipython_path"
echo "Jupyter path: $jupyter_path"
echo "IP-Cluster path: $ipcluster_path"
echo "Environment activate: $activate_path"
echo "IP-Cluster profile: $uuid"
echo "notebook: $notebook"
echo "detector: $detector"
echo "caltype: $caltype"
echo "final: $final"
echo "finalize: $finalize"
echo "cluster_cores: $cluster_cores"
echo "job ID: $SLURM_JOB_ID"

export CAL_NOTEBOOK_NAME=$notebook

# set-up enviroment
source ${activate_path}

echo "Starting influx feeder"
./cal_influx_feeder.sh $notebook $detector $caltype > /dev/null 2>&1  &

# make sure we use agg backend
export MPLBACKEND=AGG

# start an ip cluster if requested
if [ "${uuid}" != "NO_CLUSTER" ]
then
    ${ipython_path} profile create ${uuid} --parallel
    ${ipcluster_path} start --n=${cluster_cores} --profile=${uuid} --daemon &
    sleep 15
fi


echo "Running script"
${jupyter_path} nbconvert --to rst --ExecutePreprocessor.timeout=36000 --ExecutePreprocessor.allow_errors=True --TemplateExporter.exclude_input=True --execute ${nb_path}

# stop the cluster if requested
if [ "${uuid}" != "NO_CLUSTER" ]
then
    ${ipcluster_path} stop --profile=${uuid}
    profile_path=`${ipython_path} locate profile ${uuid}`
    echo "Removing cluster profile from: $profile_path"
    rm -rf $profile_path
fi

if [ "${final}" == "FINAL" ]
then
   ${finalize} $SLURM_JOB_ID
fi
killall -9 cal_influx_feeder.sh || true
