#!/bin/bash

cd ${0%${0##*/}}.

. ./setenv.sh


PARAMS="-Dboot.info=1 -Dapp.name=BGScheduler -Dlog4j.configuration=data/log4j.xml -Dlog.dir.path=log/ -Dlog.prefix=scheduler ${BGBILLING_SYSTEM_PROPERTIES}"
MEMORY="-Xmx512m"

if [ -n "$BGBILLING_MEMORY" ]; then
  MEMORY=$BGBILLING_MEMORY
fi

if [ -z "$BGBILLING_JAVA_VERSION" ]; then
  BGBILLING_JAVA_VERSION="1.8"
fi

COMMON_PARAMS="-Dnetworkaddress.cache.ttl=3600 -Djava.net.preferIPv4Stack=true"
if [ "$BGBILLING_JAVA_VERSION" = "1.8" ]; then
    COMMON_PARAMS="$COMMON_PARAMS -Djava.endorsed.dirs=${BGBILLING_SERVER_DIR}/lib/endorsed:${JAVA_HOME}/lib/endorsed"
else
    COMMON_PARAMS="$COMMON_PARAMS --add-modules java.xml.bind,java.xml.ws"
fi

CLASSPATH=${BGBILLING_SERVER_DIR}:${BGBILLING_SERVER_DIR}/lib/app/*:${BGBILLING_SERVER_DIR}/lib/ext/*

if [ ! -d "${BGBILLING_SERVER_DIR}/.run" ] ; then
    mkdir ${BGBILLING_SERVER_DIR}/.run
fi

CMD=$1

if [ "$CMD" = "debug" ]; then
    DEBUG="-enableassertions -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=5589,server=y,suspend=n"
    CMD="-estart"
fi

ALL_ARGS="${COMMON_PARAMS} ${PARAMS} ${MEMORY} -cp ${CLASSPATH} ${DEBUG} bitel.billing.server.TaskExecuter $CMD $2 $3"

if [ "$CMD" != "-estart" ]; then
    #execute command
    ${JAVA_HOME}/bin/java ${COMMON_PARAMS} -cp ${CLASSPATH} bitel.billing.server.TaskExecuter $CMD $2 $3
else
    #starting
    if [ "$BGBILLING_DOCKER" != "yes" ]; then
        nohup ${JAVA_HOME}/bin/java ${ALL_ARGS} > ./log/scheduler.out 2>&1 & echo $! > .run/bgscheduler.pid &
    else
        ${JAVA_HOME}/bin/java ${ALL_ARGS} | tee ./log/scheduler.out
    fi
fi