#!/usr/bin/bash

absolute_path() {
    # if the given path to the jbang launcher is absolute (i.e. it is either starting with / or a
    # 'letter:/' when using gitbash on windows) it is returned unchanged, otherwise we construct an absolute path
    [[ $1 = /* ]] || [[ $1 =~ ^[A-z]:/ ]] && echo "$1" || echo "$PWD/${1#./}"
}

resolve_symlink() {
    if [[ $OSTYPE != darwin* ]]; then minusFarg="-f"; fi
    sym_resolved=$(readlink ${minusFarg} $1)

    if [[ -n $sym_resolved ]]; then
        echo $sym_resolved
    else
        echo $1
    fi
}

abs_jbang_path=$(resolve_symlink $(absolute_path $0))

## resolve application jar path from script location and convert to windows path when using cygwin
jarPath=$(dirname $abs_jbang_path)/jbang.jar
if [[ $(uname) == CYGWIN* ]]; then jarPath=$(cygpath -w ${jarPath}); fi

## prefer JAVA instead of PATH to resolve `java` location
if [[ -z "$JAVA_HOME" ]]; then JAVA_EXEC="java"; else JAVA_EXEC="$JAVA_HOME/bin/java"; fi

## expose the name of the script being run to the script itself
export JBANG_FILE="$1"

## https://stackoverflow.com/questions/1668649/how-to-keep-quotes-in-bash-arguments
## attempt to ensure each argument keeps its original quoting


## run it using command substitution to have just the user process once jbang is done
eval "exec $(${JAVA_EXEC} ${JBANG_JAVA_OPTIONS} -classpath ${jarPath} dk.xam.jbang.Main "$@")"