#!/usr/bin/env bash

# Based on kotlinc.bat from the Kotlin distribution

resolveAbsolutePath() {
    # if the given path to the kscript 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#./}"
}

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

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

findJavaVersion() {
    # Note that this only loads the first component of the version, so "1.8.0_265" -> "1".
    # But it's fine because major version is 9 for JDK 9, and so on.
    regex='^.*version "([[:digit:]]+).*$'
    while read -r line; do
        if [[ "$line" =~ $regex ]]; then
            echo ${BASH_REMATCH[1]}
        fi
    done <<< $("${JAVACMD:=java}" -version 2>&1)
}

# Resolve KSCRIPT_HOME
KSCRIPT_HOME=$(dirname $(dirname $(resolveSymlinks $(resolveAbsolutePath $0))))
KSCRIPT_LIB="$KSCRIPT_HOME/bin"

# Resolve JAVA_CMD
if [ -z "$JAVACMD" -a -n "$JAVA_HOME" -a -x "$JAVA_HOME/bin/java" ]; then
    JAVACMD="$JAVA_HOME/bin/java"
fi

# OSTYPE can be: linux*, freebsd, darwin*, cygwin, msys
if [[ "$OSTYPE" == "cygwin" || "$OSTYPE" == "msys" ]]; then
  KSCRIPT_LIB=$(cygpath -w "${KSCRIPT_LIB}")
fi

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

[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xmx256M -Xms32M"

declare -a JAVA_ARGS
declare -a KOTLIN_ARGS

while [ $# -gt 0 ]; do
  case "$1" in
    -D*)
      JAVA_ARGS=("${JAVA_ARGS[@]}" "$1")
      shift
      ;;
    -J*)
      JAVA_ARGS=("${JAVA_ARGS[@]}" "${1:2}")
      if [ "x${1:2}" = "x" ]; then
        echo "error: empty -J argument"
        exit 1
      fi
      shift
      ;;
    *)
      KOTLIN_ARGS=("${KOTLIN_ARGS[@]}" "$1")
      shift
      ;;
  esac
done

# Additional Java args
JAVA_VERSION="$(findJavaVersion)"
if [[ $JAVA_VERSION -ge 9 ]]; then
  # Workaround the illegal reflective access warning from ReflectionUtil to ResourceBundle.setParent, see IDEA-248785.
  JAVA_ARGS=("${JAVA_ARGS[@]}" "--add-opens" "java.base/java.util=ALL-UNNAMED")
fi

if [[ $JAVA_VERSION < 13 ]]; then
  JAVA_ARGS=("${JAVA_ARGS[@]}" "-noverify")
fi

# KScript dependencies itself
CLASS_PATH="$KSCRIPT_LIB/*"

## execute process
"${JAVACMD:=java}" $JAVA_OPTS "${JAVA_ARGS[@]}" -classpath "$CLASS_PATH" io.github.kscripting.kscript.KscriptKt "$OSTYPE" "${KOTLIN_ARGS[@]}"
