#! /bin/sh
# -*- mode: shell-script; indent-tabs-mode: nil -*-
# Copyright (c) 2008-2024 Robert Virding
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Follow symlinks to actual program and set env variables.  We have to
# cd to each directory following symlinks to handle relative symlinks.

follow_symlink () {
    cd "$(dirname "$1")" > /dev/null
    filename="$(basename "$1")"
    if [ -h "$filename" ]; then
        follow_symlink "$(readlink "$filename")"
    else
        echo "$(pwd -P)/$filename"
    fi
}

show_help () {
    echo "Usage: `basename $0` [flags] -run-script file [args]

    -h | -help               Print this help and exit
    -e | -lfe-eval | -eval \"sexp\"
                             Evaluates the given LFE sexpr
    -erl_eval                Evaluates the given Erlang expression
    --<flag>                  Enables all flags
    -/+flag                    Enables emulator flags
    --                       Everything upto next flag is plain argument
    -extra                   Everything after this is a plain argument

    -repl repl               Sets which repl is to be used
    -prompt value            Set the LFE prompt to a user-supplied value
    -run-script \"name\"       Run the LFE script file and then terminate
    -flag | +flag            Enables/disables configuration flags to be
                             used by the Erlang VM

    Note that all flags accept being prefixed by either - or -- and the
    \"run-\" flags accept arguments to the function/script being called." >&2
}

SELF=$(follow_symlink "$0")
LFE_PROGNAME=$(echo "$0" | sed 's/.*\///') # Basically basename
LFE_BINDIR=$(dirname "$SELF")
LFE_ROOTDIR=$(dirname "$LFE_BINDIR")

export LFE_ROOTDIR
export LFE_BINDIR
export LFE_PROGNAME

ERL_EXEC="erl"
NO_SHELL=""                     # No -noshell default
EXTRA=""                        # A break
i="$#"                          # Counter of number left to processed
e=""                            # Eval flag/value

# First step over the flag section adding them to the end.
while [ "$i" -gt 0 ]; do
    s=0                         # count to be shifted
    c=0                         # count to be copied
    case "$1" in
        # Handle the -- flags here
        --)                     # Don't trim this!
            set -- "$@" "$1"
            s=1
            ;;
        # Any special handling of -- flags must come before this
        --*)                    # Remove the extra -, replace and loop
            # Repl="$(echo "$1" | cut -c 2-)"
            Repl=$(echo "$1" | sed 's/^-//')
            shift 1
            set -- "$Repl" "$@"
            s=0
            ;;
        # Handle specific single - flags first.
        -extra)                 # Everything after this is a plain argument
            # set -- "$@" "$1"
            # EXTRA="true"
            # s=1
            break               # Exit the loop
            ;;
        -e | -eval | -lfe_eval | -lfe-eval)
            # We are going to do LFE eval but using -run
            set -- "$@" "-run" "lfe_init" "do_eval"
            s=1
            ;;
        -erl_eval)              # The Erlang eval
            set -- "$@" "-eval"
            s=1
            ;;
        -h | -help)             # Show help
            $(show_help)
            exit 1
            ;;
        -run-script)
            set -- "$@" "$1"
            s=1
            ;;
        -*)                     # The standard single - stuff
            # # Only set "-noshell" if we are not past an -extra.
            # if [ "$1" == "-run-script" ] && [ "$EXTRA" != "true" ]; then
            #     NO_SHELL="-noshell"
            # fi
            set -- "$@" "$1"
            s=1
            ;;
        *)                      # Plain argument
            set -- "$@" "$1"
            s=1
            ;;

    esac
    shift $s ; i=`expr $i - $s`
done

echo "i=$i"  "$@"

# Collect everything after a -extra.
 while [ "$i" -gt 0 ]; do
     set -- "$@" "$1"
     shift ; i=`expr $i - 1`
 done
 
echo "2="  "$@"

set -- "-user" "lfe_init_new" "--" "$@"

echo "3="  "$@"


# The order of precedence for LFE libraries is as follows:
# 1) The LFE_ROOTDIR for the current bin/lfe being executed is unusurpable;
#    allowing anything else would leave LFE open to instabilities where it
#    could be executed with libraries of a different release.
# 2) A user/developer should be allowed to override anything else by updating
#    ERL_LIBS as they see fit.
# 3) A project's libraries (current directory) should be loaded automatically,
#    if they exist, but not override the previous two.
# 4) If a default library is installed in ~/.lfe/libs, then that will be added
#    last, in the event that the sought library is not picked up in any of the
#    other locations.
#
# Note that ERL_LIBS will find *either* an ebin subdir *or* lib subdir

# Find application ebin directories in lib if lib exists.

find_libs () {
    if [ -d "$1" ]; then
        echo $(find "$1" -maxdepth 1 -mindepth 1 -exec printf "%s:" {} \;)
    fi
}

# The following works for rebar and erl.mk
PROJ_LIBS=$(find_libs "./deps")

echo "4="  "$@"

# The following works for rebar3
if [ -d "$REBAR_DEPS_DIR" ]; then
    # Use $REBAR_DEPS_DIR if set...
    R3_PROJ_LIBS=$(find_libs "$REBAR_DEPS_DIR")
else
    # ... otherwise provide a sensible default
    R3_PROJ_LIBS=$(find_libs "./_build/${REBAR_PROFILE:-default}/deps"):$(find_libs "./_build/${REBAR_PROFILE:-default}/lib")
fi
LFE_HOME_LIBS=$(find_libs "$HOME"/.lfe/lib)
ALL_LIBS="$LFE_ROOTDIR":"$ERL_LIBS":"$PROJ_LIBS""$R3_PROJ_LIBS""$LFE_HOME_LIBS"
## ERL_LIBS="$ALL_LIBS" exec $ERL_EXEC  "$@"

if [ -n "$LFE_CLI_DRY_RUN" ]; then
    echo "ERL_LIBS=$ALL_LIBS" exec $ERL_EXEC "-noshell" "$@"
else
    ERL_LIBS="$ALL_LIBS" exec $ERL_EXEC "-noshell" "$@"
fi
