#!/bin/bash

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

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 "Karabo activate: $krb_activate_path"
echo "IP-Cluster profile: $uuid"

export CAL_NOTEBOOK_NAME=$notebook

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

# activate karabo if requested
if [ "${krb_activate_path}" != "NO_KRB_ACTIVATE" ]
then
    source ${krb_activate_path}
fi

# 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=16 --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} 
fi
killall -9 cal_influx_feeder.sh