#!/bin/bash

# launcher for matlab/octave/ifit data 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(){ perl -MCwd -e 'print Cwd::abs_path shift' "$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/x86_64-linux-gnux32"
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/mcplot"
TOOL="mcplot"
VERS="3.5"

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

canrun_i() {
    if ! [ -x ${LIB}/${TOOL}.m ]; then
        exit 127;
    fi
    
    # is ifit on the path?
    if ! [ `which ifit` ]; 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
}


if ( canrun_m ); then
    matlab -nosplash -nodesktop -r "addpath('${LIB}');${TOOL} $*"
elif ( canrun_i ); then
    ifit -r $*
elif ( canrun_o ); then
    octave --eval "addpath('${LIB}');${TOOL} $*"
else
    echo ":: Failed to run Matlab/iFit/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
