#!/usr/bin/arch -x86_64 /usr/bin/env bash --login
#
# Wrapper script for starting mcgui in an app on Mac OS X
#

SCRIPTDIR=`dirname $0`
BASEDIR=$SCRIPTDIR/../..


if [[ $BASEDIR == /Applications* ]];
then
    # Check if conda is already in place, shell hook activate
    if [ -f ${BASEDIR}/Contents/Resources/miniconda3/bin/conda ]; then
	MCCONDADIR=`dirname $(readlink -f ${BASEDIR}/Contents/Resources/miniconda3/bin)`
	echo Attempting shell-hook activate of MCCONDADIR=${MCCONDADIR}
	"$(${MCCONDADIR}/bin/conda shell.bash hook)"
        ret_code00=$?
	if [ "$ret_code00" != "0" ];
	then
	    echo Fallback source $MCCONDADIR/bin/activate
	    source $MCCONDADIR/bin/activate
	    ret_code00=$?
	fi
	if [ "$ret_code00" != "0" ];
	then
	    osascript -e "tell app \"System Events\" to display dialog \"Conda looks to be in place, yet something is wrong... :-( Please create an issue at https://github.com/mccode-dev/McCode/issues \""
	    exit
	fi
    else
	if [ -f ${BASEDIR}/Contents/Resources/INJECTING ]; then
	    osascript -e "tell app \"System Events\" to display dialog \"Sorry, conda injection already started - please wait until completion - of in the envent of failure create an issue at https://github.com/mccode-dev/McCode/issues \""
	    exit
	else
	    osascript -e "tell app \"System Events\" to display dialog \"Your mcstas app does not yet include a conda environment, now proceeding to download. A notification should appear again once the process is over. :-) \""
	    ret_code0=$?
	    if [ "$ret_code0" != "0" ];
	    then
		echo "User cancelled..."
		exit
	    else
		# Check if conda is on the path or not?
		conda activate &> /dev/null
		ret_code1=$?                       # True if there is a conda env loaded

		ret_code2="0"                      # Set up to skip dialogue below

		if [ "$ret_code1" = "0" ];         # We found conda
		then
		    conda deactivate &> /dev/null  # Try unloading
		    ret_code2=$?
		fi

		if [ "$ret_code2" != "0" ];        # Unloading must have failed
		then
		    COND=`which conda`
		    osascript -e "tell app \"System Events\" to display dialog \"Info: Could not unload your existing conda env ${COND}... :-( Attempting injection by Miniforge anyhow \""
		fi

		# Fetch latest Miniforge
		touch ${BASEDIR}/Contents/Resources/INJECTING
		/usr/bin/open $SCRIPTDIR/Miniforge-inject.command
		export INJECTING=1
	    fi
	fi
    fi
    if [ -z "${INJECTING}" ];
    then
	SCRIPT=${CONDA_PREFIX}/bin/mcgui
	if [ -e $SCRIPT ]
	then
	    $SCRIPT $* > /dev/null 2>&1
	else
	    osascript -e "tell app \"System Events\" to display dialog \"Sorry, your mcstas app (mcgui) can not be started, please create an issue at https://github.com/mccode-dev/McCode/issues \""
	fi
    fi
else
    osascript -e "tell app \"System Events\" to display dialog \"The app is not located in /Applications - please place the App bundle in /Applications! \""
fi

