#!/bin/sh

#
# Copyright (c) DbVis Software AB. All Rights Reserved.
#

# Script to launch the command line interface for DbVisualizer

# Function: Initializes the java version variables
init_java_version() {
  version_output=$("$JAVA_EXEC" -version 2>&1)
  is_gcj=$(expr "$version_output" : '.*gcj')
  IS_OPENJDK=$(expr "$version_output" : '.*OpenJDK')
  if [ "$is_gcj" = "0" ]; then
    java_version=$(expr "$version_output" : '.*"\(.*\)".*')
    JAVA_MAJOR_VERSION=$(expr "$java_version" : '\([0-9][0-9]*\).*')
    JAVA_MINOR_VERSION=$(expr "$java_version" : '[0-9][0-9]*\.\([0-9][0-9]*\).*')
    JAVA_MICRO_VERSION=$(expr "$java_version" : '[0-9][0-9]*\.[0-9][0-9]*\.\([0-9][0-9]*\).*')
    VER_PATCH=$(expr "$java_version" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*[\._]\([0-9][0-9]*\).*')
  fi

  if [ -z "$java_version" ] ; then
    echo "Unable to extract java version - is a supported JRE installed?"
    exit 1
  fi

  if [  "$JAVA_MAJOR_VERSION" -eq "1" ]; then
    if [  "$JAVA_MINOR_VERSION" -le "7" ]; then
      echo  "Java version $java_version is not supported. At least java 8 is required."
      exit 1
    fi
  fi
}

# If JAVA_EXEC is not set check if we're on macOS and if there is a bundled
# JRE that should be used. Otherwise use java in the PATH.
init_java_exec() {
  if [ -z "$JAVA_EXEC" ] ; then
    if [ "$DBVIS_OSTYPE" = "Darwin" ]; then
      JAVA_PATH="../../PlugIns/jre.bundle/Contents/Home/bin/java"
      if [ -f "$DBVIS_HOME/$JAVA_PATH" ]; then
        JAVA_EXEC="$DBVIS_HOME/$JAVA_PATH"
      fi
    fi
    if [ "$DBVIS_OSTYPE" = "Linux" ]; then
      JAVA_PATH="jre/bin/java"
      if [ -f "$DBVIS_HOME/$JAVA_PATH" ]; then
        JAVA_EXEC="$DBVIS_HOME/$JAVA_PATH"
      fi
    fi
  fi
  # Use java in PATH
  if [ -z "$JAVA_EXEC" ] ; then
    JAVA_EXEC=java
  fi
}

set_vars() {
  if [ -z "$DBVIS_HOME" ] ; then
    DBVIS_HOME=$(dirname "$0")
  fi
  CP="$DBVIS_HOME/resources"
  CP="$CP:$DBVIS_HOME/lib/*"
  DBVIS_OSTYPE=$(uname)
}

set_vars
init_java_exec
init_java_version "$JAVA_EXEC"

# All code up to this row is the same as in dbvisgui.sh

VM_ARGS="-Xmx768M"

if [ "$JAVA_MAJOR_VERSION" -ge "9" ]; then
  # Java 9+ found
  "$JAVA_EXEC" ${VM_ARGS} \
    -Dsun.locale.formatasdefault=true \
    -Djava.awt.headless=true \
    -Ddbvis.home="${DBVIS_HOME}" \
    @"${DBVIS_HOME}"/java9-args \
    -cp "${CP}" \
    com.onseven.dbvis.DbVisualizerCmd "$@"
elif [ "$JAVA_MAJOR_VERSION" = "1" ] && [ "$JAVA_MINOR_VERSION" = "8" ]; then
  # Java 8 found
  "$JAVA_EXEC" ${VM_ARGS}  \
    -Dsun.locale.formatasdefault=true \
    -Djava.awt.headless=true \
    -Ddbvis.home="${DBVIS_HOME}" \
    -cp "${CP}" \
    com.onseven.dbvis.DbVisualizerCmd "$@"
else
  printf "Error: At least Java 8 is required. Below is the version currently being used:\n"
  "$JAVA_EXEC" -version
  exit 2
fi
