#!/bin/bash

# Copyright 2018-present, Yudong (Dom) Wang
#
# Licensed 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.

# chkconfig: 345 99 01
# description: soler

# -----------------------------------------------------------------------------
# Soler Script
# -----------------------------------------------------------------------------

JAVA_BIN=$JAVA_HOME/bin/java

SOLER_OK=0
SOLER_ERR=1
SOLER_PID=""

SOLER_HOME="@SOLER_HOME@"
if [ ! -d $SOLER_HOME ]; then
    cd `dirname $0`/..
    SOLER_HOME=`pwd`
fi

SOLER_LOG_DIR=$SOLER_HOME/logs
SOLER_LOG=$SOLER_LOG_DIR/soler-client.log
SOLER_APP=$SOLER_HOME/soler-client.jar

# Source function library
INIT_FUNCTIONS="/etc/init.d/functions"
if [ -f $INIT_FUNCTIONS ]; then
    . $INIT_FUNCTIONS
fi

if [ ! -d $SOLER_LOG_DIR ]; then
    mkdir -p $SOLER_LOG_DIR
fi

pid() 
{
    SOLER_PID=`ps -ef | grep -v grep | grep "$SOLER_APP" |awk '{print $2}'`
}

status() 
{
    pid
    if [ -n "$SOLER_PID" ]; then
        echo "Soler client PID <$SOLER_PID> is running."
    else
        echo "Soler client is stopped."
    fi
}

start() 
{
    pid
    if [ -n "$SOLER_PID" ]; then
        status
        return $SOLER_OK
    fi

    if [ ! -f "$JAVA_BIN" ]; then
        JAVA_BIN=`which java`
        if [ ! -f "$JAVA_BIN" ]; then
            JAVA_BIN=java
        fi
    fi

    nohup $JAVA_BIN -jar $SOLER_APP >>$SOLER_LOG 2>&1 &
    status
}

stop() 
{
    pid
    if [ -z "$SOLER_PID" ]; then
        status
        return $SOLER_OK
    fi

    echo -e "Stopping the soler client PID <$SOLER_PID> ...\c"
    kill -9 $SOLER_PID >> $SOLER_LOG 2>&1
    status
}

# See how we were called.
case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    status)
        status
    ;;
    restart)
        stop
        start
    ;;
    *)
    echo $"Usage: $0 {start|stop|status|restart}"
    exit $SOLER_ERR
esac
