#!/usr/bin/env bash
# Wrapper script for @P@display-vtk-py

# First ensure that we follow symlink if needed
LINK=`readlink $0`

# Am I a symlink?
if [ "x$LINK" != "x" ]; then
    LIB=`dirname $LINK`
else
    LIB=`dirname $0`
fi
LIB="$LIB/../tools/Python/@P@display/VTK/"
TOOL="@P@display"
VERS="@MCCODE_VERSION@"

VTKPYTHON=`which vtkpython`
VTKPYTHON_LOCATION=`dirname $VTKPYTHON`
export PYTHONPATH=$VTKPYTHON_LOCATION:VTKPYTHON_LOCATION/../lib
export DYLD_LIBRARY_PATH=$PYTHONPATH
export LD_LIBRARY_PATH=$PYTHONPATH

canrun() {
    if ! [ -x ${LIB}/${TOOL}.py ]; then
        exit 127;
    fi
    modules="vtk"
    cmd=""
    for name in ${modules}; do
        cmd="${cmd}import ${name}; "
    done
    vtkpython -c "${cmd}"
}

if ( canrun ); then

    TRACEFILE=`mktemp -u /tmp/trace.XXX`
    echo
    echo Running ${TOOL}.py for Python-VTK output 
    echo - please give a few \[return\] if nothing happens!!
    echo
    mcrun  $* --trace --no-output-files -n1e2 > ${TRACEFILE}
    vtkpython ${LIB}/${TOOL}.py ${TRACEFILE}
    rm ${TRACEFILE}

else
    echo ":: Failed to run Python ${TOOL}, trying old Perl version."
    echo ":: If this fails too, consider reinstalling ${TOOL}."
    echo ""

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