#!/bin/sh

#+-----------------------
#|Elnetw Launcher
#|
#|ランチャーjarを見付け出して起動させる。
#+-----------------------

# functions

#########################
# add_java_arg
#   javaコマンドへ渡す引数
# $1=arg
#########################
add_java_arg() {
  tt_java_args="${tt_java_args} $1"
}

#########################
# add_arg
#   アプリケーションへ渡す引数
# $1=arg
#########################
add_arg() {
  tt_args="${tt_args} $1"
}

#########################
# add_classpath_dir
#   $1がディレクトリとして存在するのならば、クラスパスへ追加する
# $1=arg
#########################
add_classpath_dir() {
  test -d "$1" && add_arg "-L$1"
}

#========================
# main
#========================


# JAVA_HOMEがない
if test -z "${JAVA_HOME}"; then
  # PATH環境変数の中にjavaが存在する
  if which java >/dev/null 2>&1; then
    JAVA_BIN="$(which java)"
  else
    # 見つからないときはエラー
    echo
    echo "ERROR: JAVA_HOME not found in your environment."
    echo "Please set the JAVA_HOME variable in your environment to match the"
    echo "location of your Java installation"
    echo
    exit 1
  fi
else
  JAVA_BIN="${JAVA_HOME}/bin/java"
fi

if test \! -x "${JAVA_BIN}"; then
  echo
  echo "ERROR: JAVA_HOME is set to an invalid directory."
  echo "JAVA_HOME = \"${JAVA_HOME}\""
  echo "Please set the JAVA_HOME environment variable to match the"
  echo "  location of your Java installation"
  echo " or install JRE \(not JDK\) to store \'java\' in your PATH."
  echo
  exit 1
fi

# 現在の作業ディレクトリを保存する
WORKDIR="$(pwd)"

# バッチファイルが置いてある場所の上のディレクトリに移動し、ディレクトリパスを保存
cd "$(dirname $0)"
BATCH_DIR="$(pwd)"
cd ..
BATCH_PARENT_DIR="$(pwd)"
cd "${WORKDIR}"

# binディレクトリから直接起動させたときは上のディレクトリにする。
if test "${BATCH_DIR}" = "${WORKDIR}"; then cd ..; fi

# standalone jar が存在するならポータブル設定
for i in "${BATCH_PARENT_DIR}"/target/elnetw-*-jar.jar; do
  if test "$i" = "${BATCH_PARENT_DIR}/target/elnetw-*-jar.jar"; then
    # standalone jar is not found
    break
  elif test -z "${_dist_jar}"; then
    _dist_jar=$i
  else
    echo
    echo "ERROR: multiple standalone jars"
    echo "Please exec 'mvn clean install' in source directory."
    echo
    exit 1
  fi
done

if test ! -z "${_dist_jar}"; then
  TTJAR="${_dist_jar}"
  add_java_arg '-Dconfig.portable=true'
elif test -e "${BATCH_PARENT_DIR}/bin/launcher.jar"; then
  TTJAR="${BATCH_PARENT_DIR}/bin/launcher.jar"
else
  # jarが見つからない
  echo
  echo "ERROR: Usable jar is not found."
  echo "Please re-install or,"
  echo " if you compile from source, run 'mvn install'"
  echo "  in elnetw source directory."
  echo
  exit 1
fi


while true; do
  case "$1" in
    -J)   add_java_arg "$2"; shift;;
    -J*)  add_java_arg "${1#-J}";;
    *)    break;;
  esac

  shift
done

add_classpath_dir "${HOME}/.elnetw/lib"
add_classpath_dir "${BATCH_PARENT_DIR}/lib"


# load ~/.elnetw/launcher.cfg
test -x "${HOME}/.elnetw/launcher.cfg" && source "${HOME}/.elnetw/launcher.cfg"


"${JAVA_BIN}" ${tt_java_args} -jar "${TTJAR}" ${tt_args} $@
