#!/bin/bash

# launcher for matlab/octave 3d geometry plotter

############################################
# 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
############################################

LIB="${MCCODE_TOOLDIR}/matlab/mcdisplay"
TOOL="mcdisplay"
MCRUN="mcrun"
VERS="3.5.39_nightly"

canrun_m() {
    if ! [ -x ${LIB}/${TOOL}.m ]; then
        exit 127;
    fi
    
    # is matlab on the path?
    if ! [ `which matlab` ]; then
            exit 127;
    fi
}

canrun_o() {
    if ! [ -x ${LIB}/${TOOL}.m ]; then
        exit 127;
    fi
    
    # is octave on the path?
    if ! [ `which octave` ]; then
            exit 127;
    fi
}

# defaults
if ( canrun_m ); then RUN_MATLAB=1; else RUN_MATLAB=0; fi
if ( canrun_o ); then RUN_OCTAVE=1; else RUN_OCTAVE=0; fi

# handle input options, overriding defaults
while getopts hom flag
do
  case "${flag}" in
  o)
    RUN_OCTAVE=1
    RUN_MATLAB=0
  ;;
  m)
    RUN_MATLAB=1
    RUN_OCTAVE=0
  ;;
  *)
    echo "usage:"
    echo "  $0 INSTR"
    echo "    Displays the given McCode 3D model with its defaults/current parameters."
    echo "  $0 INSTR name1=value1 ..."
    echo "    Displays the given McCode model with given parameters."
    echo "  $0 [-png|-jpg|-fig|-eps|-pdf|-tif] INSTR name1=value1 ..."
    echo "    Same as above, and specifies an output file format to generate."
    echo "    Possible save_as are -png -pdf -fig -tif -jpg -eps"
    echo "  $0 --inspect=COMP INSTR name1=value1 ..."
    echo "    Same as above, and only plot component names that match 'COMP', given as"
    echo "      a single component word for partial match, such as Monitor"
    echo "      a component interval such as Monok:Sample or 2:10 or 2:end"
    echo "  $0 -m INSTR ..."
    echo "        Explicitely request to use Matlab"
    echo "  $0 -o INSTR ..."
    echo "        Explicitely request to use Octave"
    exit 1
    ;;
  esac
done
shift $((OPTIND-1))

if [ "$RUN_MATLAB" == "1" ]; then
    matlab -nosplash -nodesktop -r "addpath('${LIB}');${TOOL} ${MCRUN} $*"
elif [ "$RUN_OCTAVE" == "1" ]; then
    octave --eval "addpath('${LIB}');${TOOL} ${MCRUN} $* ; disp('--> Right-click in axis for toggles etc.'); disp('Close window to exit mcdisplay-matlab ...'); set(gcf,'closerequestfcn','exit'); waitfor(gcf);"
else
    echo ":: Failed to run Matlab/Octave ${TOOL}, trying default ${TOOL} instead."
    echo ":: If this fails too, consider reinstalling ${TOOL}."
    echo ""

    # Try old Perl-version of mcplot if Python version cannot run
    ${TOOL} $*
fi
