#!/bin/bash

# macOS: The variable DYLD_LIBRARY_PATH is unset because of System Integrity Protection.
[ $EXECUTOR_DYLD_LIBRARY_PATH ] && export DYLD_LIBRARY_PATH=$EXECUTOR_DYLD_LIBRARY_PATH

# Portable version
prepend_path()
{
  if eval test -z "\"\$$1\"" || ! eval test -z "\"\${$1##*:$2:*}\"" -o -z "\"\${$1%%*:$2}\"" -o -z "\"\${$1##$2:*}\"" -o -z "\"\${$1##$2}\"" ; then
    eval "export $1=\"$2\":\$$1"
  fi
}
prepend_path LD_LIBRARY_PATH $PREPEND_LIBRARY_PATH      # Linux
prepend_path DYLD_LIBRARY_PATH $PREPEND_LIBRARY_PATH    # macOS

rxapi >/dev/null & # Workaround to avoid crash at first execution

# If the variable OOREXXSHELL_RLWRAP is defined
# then ooRexxShell will use a basic parse pull because rlwrap will manage the readline
# otherwise it will use the bash readline.
# rlwrap completion is not working with names like gci-try. --break-chars fixes this problem.
# The space character in filenames is not supported (not escaped "\ ").
# A negative histsize means "don't modify the history file". ooRexxShell takes care of the history file.
[ -x "`which rlwrap`" ] && export OOREXXSHELL_RLWRAP="rlwrap --no-warnings --break-chars='' --complete-filenames --command-name=oorexxshell --histsize=-300"

# Don't use rlwrap if ooRexxShell is not interactive.
# I don't want the output be polluted by the cleaning of the bracketed paste mode.
# ooRexxShell is interactive if stdin, stdout and stderr are associated with a terminal.
[ -t 0 -a -t 1 -a -t 2 ] || export OOREXXSHELL_RLWRAP=

while true
do
    $OOREXXSHELL_RLWRAP rexx oorexxshell.rex "$*"
    status=$?
    # echo "status=" $status
    if test $status -ne 200; then break; fi
done

# When using rlwrap, the terminal is in bracketed paste mode after leaving oorexxShell.
# Running the command printf '\e[?2004l' in the terminal clears the bracketed paste mode.
[ "$OOREXXSHELL_RLWRAP" ] && printf '\e[?2004l'

exit $status

# Remember
#   -- When possible, use a history file specific for ooRexxShell
#   -- For the moment, don't use portableStateHome or stateHome because it doesn't work with rlwrap
#   -- Maybe will work if the environment variable RLWRAP_HOME is defined
# Problem:
#   The variables portableStateHome and stateHome are not yet defined.
#   They will be defined by oorexxshell.rex
