#!/usr/bin/env bash

# Function to provide "readlink -f" even on systems missing -f:
readlinkf(){
    perl -MCwd -e 'print Cwd::abs_path shift' "$1";
}

if [[ 0 == 1 ]]; then
  # Legacy McCode PATH setup 
  TOPENV="$0"

  # Check if we are being called with a non-full path
  if [[ $TOPENV != "/"* ]]; then
    TOPENV="$PWD/$TOPENV"
  fi

  TOPENV=`readlinkf "$TOPENV"`
  TOPENV=`dirname $TOPENV`
else
  TOPENV=$( dirname $( readlinkf ${BASH_SOURCE[0]} ) )
fi

############################################
# Start of standard CMake-generated ENV preamble
set -e
FILE=${0}
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=/usr/bin
MCCODE_RESOURCEDIR="${MCCODE_BINDIR}/../share/mcxtrace/resources"
# End of preamble
############################################

ARCH=`uname -m`
UNAME=`uname -s`

# On macOS, shorten TMPDIR 
if [[ ${UNAME} = Darwin* ]]; then
    export TMPDIR=/tmp
    OSXVER=`sw_vers -productVersion|cut -f 1 -d.`
fi

export PATH=$MCCODE_BINDIR:$PATH

export MCXTRACE=$MCCODE_RESOURCEDIR

# Check if we are running with miniconda-provided python libs and set PYTHONPATH accordingly
if [ -d "$MCXTRACE/miniconda3" ]; then
    export PATH=$TOPENV/miniconda3/bin:$PATH
    #Activation hook for conda 
    _conda_bindir="$MCXTRACE/miniconda3/bin"
    function conda() {
	unset conda
	eval "$(${_conda_bindir}/conda shell.bash hook 2> /dev/null)"
	conda "$@"
    }
    conda activate $MCXTRACE/miniconda3
    export PS1='(mcxtrace-v3.5.39/miniconda3) \W \$ '
else
    export PS1='mcxtrace-v3.5.39 env \W \$ '
fi

 
if [ -d "$MCXTRACE/share/NCrystal/python/" ]; then
    export PYTHONPATH=$MCXTRACE/share/NCrystal/python/:$PYTHONPATH
fi

echo
echo The new shell started here is now set up for running this version of mcxtrace:
echo
mcxtrace -v
echo
echo To end using this version of mcxtrace, exit this shell.
echo
if ! [ "${CONDA_PREFIX}x" == "x" ]; then
    echo \( Using CONDA env placed in 
    echo    ${CONDA_PREFIX} \)
    echo
fi

if [ -x ${SHELL} ]; then
  ${SHELL}
else
  /bin/sh
fi

