#!/bin/sh
# ----------------------------------------------------------------------------
#
# Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# WSO2 Inc. licenses this file to you 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.
#
# ----------------------------------------------------------------------------
# Execution Script for Testgrid
#
# Environment Variable Prerequisites
#
#   TESTGRID_HOME      (Optional) Home for Testgrid runtime, If not provided a default home will be created
#
#   JAVA_HOME           Must point at your Java Development Kit installation.
#
#   JAVA_OPTS           (Optional) Java runtime options used when the commands
#                       is executed.
#
# NOTE: Borrowed generously from Apache Tomcat startup scripts.
# -----------------------------------------------------------------------------

echo "__          _______  ____ ___    _______        _    _____      _     _ "
echo "\ \        / / ____|/ __ \__ \  |__   __|      | |  / ____|    (_)   | |"
echo " \ \  /\  / / (___ | |  | | ) |    | | ___  ___| |_| |  __ _ __ _  __| |"
echo "  \ \/  \/ / \___ \| |  | |/ /     | |/ _ \/ __| __| | |_ |  __| |/ _  |"
echo "   \  /\  /  ____) | |__| / /_     | |  __/\__ \ |_| |__| | |  | | (_| |"
echo "    \/  \/  |_____/ \____/____|    |_|\___||___/\__|\_____|_|  |_|\____|"
echo ""                                                                         
                                                                         
BASE_DIR=$PWD
cygwin=false;
darwin=false;
os400=false;
mingw=false;
case "`uname`" in
CYGWIN*) cygwin=true;;
MINGW*) mingw=true;;
OS400*) os400=true;;
Darwin*) darwin=true
        if [ -z "$JAVA_HOME" ] ; then
		   if [ -z "$JAVA_VERSION" ] ; then
			 JAVA_HOME=$(/usr/libexec/java_home)
           else
             echo "Using Java version: $JAVA_VERSION"
			 JAVA_HOME=$(/usr/libexec/java_home -v $JAVA_VERSION)
		   fi
	    fi
        ;;
esac

# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '.*/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

# set Testgrid distribution location
TESTGRID_DISTRIBUTION=`cd "$PRGDIR" ; pwd`

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
  [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
  [ -n "$TESTGRID_DISTRIBUTION" ] && TESTGRID_DISTRIBUTION=`cygpath --unix "$TESTGRID_DISTRIBUTION"`
fi

# For OS400
if $os400; then
  # Set job priority to standard for interactive (interactive - 6) by using
  # the interactive priority - 6, the helper threads that respond to requests
  # will be running at the same priority as interactive jobs.
  COMMAND='chgjob job('$JOBNAME') runpty(6)'
  system $COMMAND

  # Enable multi threading
  QIBM_MULTI_THREADED=Y
  export QIBM_MULTI_THREADED
fi

# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
  [ -n "$TESTGRID_DISTRIBUTION" ] &&
    TESTGRID_DISTRIBUTION="`(cd "$TESTGRID_DISTRIBUTION"; pwd)`"
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi

if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD=java
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  exit 1
fi

# if JAVA_HOME is not set we're not happy
if [ -z "$JAVA_HOME" ]; then
  echo "You must set the JAVA_HOME variable before running Testgrid."
  exit 1
fi

# if TESTGRID_HOME is not set we're not happy
if [ -z "$TESTGRID_HOME" ]; then
  echo "TESTGRID_HOME is not set, system will setup a default location"
else
  echo "Testgrid Home is set to : " $TESTGRID_HOME
fi

# ----- Process the input command ----------------------------------------------

for c in "$@"
do
    if [ "$c" = "--debug" ] || [ "$c" = "-debug" ] || [ "$c" = "debug" ]; then
          CMD="--debug"
    elif [ "$CMD" = "--debug" ] && [ -z "$PORT" ]; then
          PORT=$c
    fi
done

if [ "$CMD" = "--debug" ]; then
  if [ "$PORT" = "" ]; then
    echo "Please specify the debug port after the --debug option"
    exit 1
  fi
  if [ -n "$JAVA_OPTS" ]; then
    echo "Warning !!!. User specified JAVA_OPTS will be ignored, once you give the --debug option."
  fi
  JAVA_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=$PORT"
  echo "Please start the remote debugging client to continue..."
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
  TESTGRID_DISTRIBUTION=`cygpath --absolute --windows "$TESTGRID_DISTRIBUTION"`
  CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
  JAVA_ENDORSED_DIRS=`cygpath --path --windows "$JAVA_ENDORSED_DIRS"`
fi

# Setting the classpath
export CLASSPATH=$TESTGRID_DISTRIBUTION/lib/*

# ----- Execute The Requested Command -----------------------------------------

$JAVACMD \
	-Xms256m -Xmx1024m \
	-XX:+HeapDumpOnOutOfMemoryError \
	-XX:HeapDumpPath="$TESTGRID_DISTRIBUTION/heap-dump.hprof" \
	$JAVA_OPTS \
	-Djava.security.egd=file:/dev/./urandom \
	-Dfile.encoding=UTF8 \
	-Dlog4j.configurationFile=$TESTGRID_DISTRIBUTION/log4j2.xml \
	org.wso2.testgrid.core.Main "$@"
