#!/bin/sh

if [ "$JAVA_HOME" != "" ]; then
  JAVA="$JAVA_HOME/bin/java"
else
  JAVA=java
fi

echo "JAVA: "$JAVA

if readlink -f "$0" > /dev/null 2>&1
then
  BIN_PATH=$(readlink -f $0)
else
  BIN_PATH=$(pwd -P)
fi

#APP_HOME=${BIN_PATH%"/bin"*}
APP_HOME=${BIN_PATH%"/"*}
echo "APP_HOME: "$APP_HOME

APP_JAR=$(find "$APP_HOME" -maxdepth 1 -name "${project.name}*\.jar" | head -n 1)
if [ -z "$APP_JAR" ]; then
 echo "[ERROR]Not found main jar file"
 exit 1
fi

echo "APP_JAR: "$APP_JAR

echo "[INFO]Start the server; home=$APP_HOME"

CPS=$(ps -e -opid,cmd | grep -i "^[0-9]* .*/java .*-Dapplication.home.dir=$APP_HOME .*${project.name}.*\.jar" | grep -v "grep" | head -n 1 | awk '{print $1}')

if [ -n "$CRACKPS" ]; then
  echo "[ERROR]Server is running;"
  exit 1
else
  JAVAOPTS="-Xms512m -Xmx1024m -Xmn256m -Xss1024k"
  APPOPTS="-Dfile.encoding=UTF-8 -Dapplication.home.dir=$APP_HOME -Dlogging.config=./config/logback-spring.xml"
  echo "[INFO]Application options: $APPOPTS"
  $JAVA $JAVAOPTS $APPOPTS "-jar" $APP_JAR "--spring.config.file=$APP_HOME/config/application.properties" 2>&1 >/dev/null &
  #echo $JAVA $JAVAOPTS "-jar" $APP_JAR
  exit 0
fi