#!/bin/sh
PORT="@profiles.server.port@"
BASEDIR=`dirname $0`/..
BASEDIR=`(cd "$BASEDIR"; pwd)`
SHELL_NAME="start"
CDATE=$(date "+%Y-%m-%d")
CTIME=$(date "+%H:%M:%S")
PROJECT_NAME="@project.artifactId@";
MAIN_CLASS="$PROJECT_NAME-@project.version@.jar";
LOG_PATH="@profiles.log.path@/$PROJECT_NAME"
GC_PATH=$LOG_PATH/PROJECT_NAME"-gc.log"
HS_ERR_PATH=$LOG_PATH/PROJECT_NAME"-hs_err.log"
HEAP_DUMP_PATH=$LOG_PATH/PROJECT_NAME"-heap_dump.hprof"
TEMP_PATH=$LOG_PATH/temp/
SHELL_LOG="${BASEDIR}/${SHELL_NAME}.log"
SUCCESS=0
FAIL=9

#写日志
writelog() {
  LOGINFO=$1
  echo "${CDATE} ${CTIME}: ${SHELL_NAME} : ${LOGINFO}" >>${SHELL_LOG}
  echo ${LOGINFO}
}


if [ ! -n "$PORT" ]; then  
	writelog $"Usage: $0 {port}"
	exit $FAIL
fi
if [ ! -d $LOG_PATH ]; 
then     
    mkdir -p $LOG_PATH; 
fi
if [ ! -d $TEMP_PATH ]; 
then     
    mkdir -p $TEMP_PATH; 
fi
#-z STRING  如果STRING的长度为零则为真 ，即判断是否为空，空即是真；
if [ -z "$JAVACMD" ] ; then
  #-n STRING  如果STRING的长度非零则为真 ，即判断是否为非空，非空即是真；
  if [ -n "$JAVA_HOME" ] ; then
    #-x FILE  如果 FILE 存在且是可执行的则为真。
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD=`which java`
	   writelog  "Error: JAVA_HOME is not defined correctly.$JAVACMD"
    #exit $ERR_NO_JAVA
  fi
fi
#-x FILE  如果 FILE 存在且是可执行的则为真。
if [ ! -x "$JAVACMD" ] ; then
  writelog "We cannot execute $JAVACMD"
  exit $ERR_NO_JAVA
fi

if [ -e "$BASEDIR" ]
then
  JAVA_OPTS="-Xms1024M -Xmx2048M -Xss256K -XX:+UseAdaptiveSizePolicy -XX:+UseParallelGC -XX:+UseParallelOldGC -XX:GCTimeRatio=39 -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:$GC_PATH -XX:+HeapDumpOnOutOfMemoryError -XX:ErrorFile=$HS_ERR_PATH -XX:HeapDumpPath=$HEAP_DUMP_PATH"
fi

CLASSPATH=$CLASSPATH_PREFIX:
EXTRA_JVM_ARGUMENTS=""

cd "$BASEDIR/boot";

writelog "starting application $PROJECT_NAME......"
exec "$JAVACMD" $JAVA_OPTS \
				$EXTRA_JVM_ARGUMENTS \
				-Dapp.name="$PROJECT_NAME" \
				-Dapp.port="$PORT" \
				-Dbasedir="$BASEDIR" \
				-Djava.io.tmpdir=$TEMP_PATH \
				-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6913 \
				-jar $MAIN_CLASS \
				> /dev/null &
				
for i in {1..60}
do
	jcpid=`ps -ef | grep -v "grep" | grep "$MAIN_CLASS" | grep "app.port=$PORT" | sed -n '1P' | awk '{print $2}'`
	if [ $jcpid ]; then
		writelog "The $PROJECT_NAME start finished, PID is $jcpid"
		exit $SUCCESS
	else
		writelog "starting the application .. $i"
		sleep 1
	fi
done
writelog "$PROJECT_NAME start failure!"
