#!/usr/bin/env bash

set -e -u -o pipefail

PROBCOMMAND=prob

# Shell wrapper for PROBCOMMAND
# Run this script to start ProB Tcl/Tk

export TRAILSTKSIZE=1M

# comment in and adapt the next line to point to the Tcl/Tk dynamic library
# if you get a message "Unable to start Tcl/Tk" when trying to start ProB
# export SP_TCL_DSO=/opt/homebrew/Cellar/tcl-tk/8.6.13_1/lib/libtcl8.6.dylib
# The shell script below will try and auto-detect Homebrew and MacPorts 8.6

echo "Starting ProB Tcl/Tk"
#echo `readlink "$0"` 

# dirname
if [ -h "$0" ]
then
    realname=`readlink "$0"`
    dirname=`dirname "$realname"`
else
    dirname=`dirname "$0"`
fi

echo "Operating System: $OSTYPE"
echo "Directory: $dirname"
#cd $dirname
#ls

if [ -z "${SP_TCL_DSO:-}" ]; then
       echo "SP_TCL_DSO variable for Tcl/Tk location is not set"
else
    if [[ -e "${SP_TCL_DSO}" ]]; then
       echo "SP_TCL_DSO variable is set to ${SP_TCL_DSO} and points to a valid location"
    else
       echo "### SP_TCL_DSO variable value ${SP_TCL_DSO} points to an invalid location!"
       if [[ "$OSTYPE" == "darwin"* ]]; then
           SP_TCL_DSO=""
       fi
    fi
fi

if [[ "$OSTYPE" == "darwin"* && -z "${SP_TCL_DSO:-}" ]]; then
    echo "Trying to set SP_TCL_DSO (Tcl/Tk location) for Homebrew (ARM)"
    for f in /opt/homebrew/Cellar/tcl-tk*/8.6*/lib/libtcl8.6.dylib; do
        ## Check if the glob gets expanded to an existing file
        ## If not, f here will be exactly the pattern above
        ## and the exists test will evaluate to false.
        [ -e "$f" ] && export SP_TCL_DSO="$f" || echo "Homebrew (ARM) Tcl/Tk does not exist"
        ## break after the first iteration
        break
    done
    if [[ -z "${SP_TCL_DSO:-}" ]]; then
        echo "Trying to set SP_TCL_DSO (Tcl/Tk location)  for Homebrew (x86_64)"
        for f in /usr/local/Cellar/tcl-tk/8.6*/lib/libtcl8.6.dylib; do
            [ -e "$f" ] && export SP_TCL_DSO="$f" || echo "Homebrew (x86_64) Tcl/Tk does not exist"
            break
        done
    fi
    if [[ -z "${SP_TCL_DSO:-}" ]]; then
        echo "Trying to set SP_TCL_DSO (Tcl/Tk location)  for MacPorts"
        f=/opt/local/lib/libtcl8.6.dylib
        [ -e "$f" ] && export SP_TCL_DSO="$f" || echo "MacPorts Tcl/Tk does not exist"
    fi
    if [[ ! -z "${SP_TCL_DSO:-}" ]]; then
        echo "Found Tcl/Tk, setting SP_TCL_DSO = ${SP_TCL_DSO}"
    else
        echo "### Unable to locate Tcl/Tk installation"
        echo "### Use for example homebrew (https://brew.sh) to install Tcl/Tk"
        echo "### This can be done with the command: brew install tcl-tk"
    fi
fi

if [[ -e "$dirname/$PROBCOMMAND" ]]; then
    echo "$dirname/$PROBCOMMAND" "$@"
    "$dirname/$PROBCOMMAND" "$@"
else
    echo "### Cannot find ProB executable: $dirname/$PROBCOMMAND"
fi
