#!/usr/bin/env bash
# Wrapper script for mcjupyter

############################################
# Start of standard CMake-generated preamble
set -e
FILE=${0}
# First, probe if we are calling script at
# install-time (postinst/postrm) or we are 
# running in an installation "userland"
SCRIPT=`basename $FILE`
if [[ ${SCRIPT} == *.postinst || ${SCRIPT} == *.postrm || ${SCRIPT} == *rpm-tmp* ]];
  then
  MCCODE_BINDIR=/usr/bin
else
  readlinkf(){ python3 -c 'import sys,pathlib
print(pathlib.Path(sys.argv[1]).resolve().absolute())' "$1"
  }
  LINK=$(readlinkf ${FILE}||true)
  if [ "x${LINK}" != "x" ]
 then
    FILE=${LINK}
  fi
  MCCODE_BINDIR="$( cd -P "$( dirname "${FILE}" )" && pwd )"
fi
MCCODE_TOOLDIR="${MCCODE_BINDIR}/../share/mcstas/tools"
MCCODE_LIBDIR="${MCCODE_BINDIR}/../lib"
MCCODE_RESOURCEDIR="${MCCODE_BINDIR}/../share/mcstas/resources"
if [ -d "${MCCODE_TOOLDIR}" ]
 then
    MCCODE_TOOLDIR="$( cd -P "${MCCODE_TOOLDIR}" && pwd )"
else
    MCCODE_TOOLDIR=""
fi
if [ -d "${MCCODE_LIBDIR}" ]
 then
    MCCODE_LIBDIR="$( cd -P "${MCCODE_LIBDIR}" && pwd )"
else
    MCCODE_LIBDIR=""
fi
if [ -d "${MCCODE_RESOURCEDIR}" ]
 then
    MCCODE_RESOURCEDIR="$( cd -P "${MCCODE_RESOURCEDIR}" && pwd )"
else
    MCCODE_RESOURCEDIR=""
fi
# End of standard preamble
############################################

TOOL="mcrun"
UTILDIR="${MCCODE_TOOLDIR}/Python/$TOOL"

# Check if we are in / - in that case cd to $HOME
if [[ ${PWD} = / ]]; then
    cd $HOME
fi

#NB: miniconda should be installed next to the tool folder:
if [ -d "${MCCODE_TOOLDIR}/../miniconda3" ]; then
    source "${MCCODE_TOOLDIR}/../miniconda3/bin/activate" "${MCCODE_TOOLDIR}/../miniconda3"
    export PATH=${MCCODE_TOOLDIR}/../miniconda3/bin/:$PATH
fi

# FIXME: NCrystal should be used via own package/infrastructure
if [ "x" == "x1" ]; then
    if [ -d "${MCCODE_TOOLDIR}/../share/NCrystal/python" ]; then
        export PYTHONPATH="${MCCODE_TOOLDIR}/../share/NCrystal/python:$PYTHONPATH"
    fi
fi

canrun() {
    if ! [ -x "${MCCODE_BINDIR}/mcstas-pygen" ]; then
        exit 127;
    fi
}

if ( canrun ); then
    INSTR=$1 # We can actually assume a single input here
    BASE=`basename ${INSTR} .instr`
    JUPYBK="${BASE}_generated.ipynb"
    mcstas-pygen ${INSTR}
    sed s/INSTRUMENT/${BASE}/g ${UTILDIR}/template.ipynb.in > ${JUPYBK}
    jupyter lab ${JUPYBK}
else
    mcstas_errmsg Failed to run Python ${TOOL} - permissions or missing dependencies\?
fi
