#!/bin/sh
#
# Shell script to start the XL TestView Server
#

absdirname ()
{
  _dir="`dirname \"$1\"`"
  cd "$_dir"
  echo "`pwd`"
}

resolvelink() {
  _dir=`dirname "$1"`
  _dest=`readlink "$1"`
  case "$_dest" in
  /* ) echo "$_dest" ;;
  *  ) echo "$_dir/$_dest" ;;
  esac
}

# Source optional settings from common locations
for cfg in /etc/sysconfig/xl-testview /etc/default/xl-testview; do
  if [ -f $cfg ]; then
    . $cfg
  fi
done

# Get Java executable
if [ -z "$JAVA_HOME" ] ; then
  JAVACMD=java
else
  JAVACMD="${JAVA_HOME}/bin/java"
fi

if [ -z "$XLT_UMASK" ] ; then
  # by default ensure files are only readable for the user running XL TestView
  XLT_UMASK=0077
fi
umask $XLT_UMASK

# Get JVM options
if [ -z "$XLT_SERVER_MEM_OPTS" ] ; then
  XLT_SERVER_MEM_OPTS="-Xmx1024m -XX:MaxPermSize=256m"
fi

if [ -z "$XLT_SERVER_OPTS" ] ; then
  XLT_SERVER_OPTS=""
fi

# Get server home dir
if [ -z "$XLT_SERVER_HOME" ] ; then
  self="$0"
  if [ -h "$self" ]; then
    self=`resolvelink "$self"`
  fi
  BIN_DIR=`absdirname "$self"`
  XLT_SERVER_HOME=`dirname "$BIN_DIR"`
elif [ ! -d "$XLT_SERVER_HOME" ] ; then
  echo "Directory $XLT_SERVER_HOME does not exist"
  exit 1
fi

cd "$XLT_SERVER_HOME"

# Build server classpath
XLT_SERVER_CLASSPATH='conf:ext'
for each in `ls hotfix/*.jar lib/*.jar plugins/*.jar 2>/dev/null`
do
  if [ -f $each ]; then
    XLT_SERVER_CLASSPATH=${XLT_SERVER_CLASSPATH}:${each}
  fi
done

ls plugins/* > /dev/null 2>&1
if [ $? -eq 0 ]; then
  for expandedPluginDir in plugins/*
  do
    if [ -d $expandedPluginDir ]; then
      XLT_SERVER_CLASSPATH=${XLT_SERVER_CLASSPATH}:${expandedPluginDir}
    fi
  done
fi

if $JAVACMD -version 2>&1 | grep -qi 'openjdk .*1.8'; then
  echo "WARNING: SSL support is broken in OpenJDK 1.8. You might not be"
  echo "         able to register your copy of XL TestView."
  echo "         Please contact XebiaLabs support <support@xebialabs.com>"
  echo "         to obtain a license."
fi

# Run server
$JAVACMD $XLT_SERVER_MEM_OPTS $XLT_SERVER_OPTS -classpath "${XLT_SERVER_CLASSPATH}" com.xebialabs.xltest.Main "$@"
