#!/bin/sh
### BEGIN INIT INFO
# Provides:          kros-gate
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: KROS Gate control
### END INIT INFO

MODULE_NAME=kros-gate
MODULE_HOME=/opt/$MODULE_NAME
LOG_HOME=/var/log/$MODULE_NAME
MODULE_LOG=$LOG_HOME/wrapper.log
MODULE_ERR=$LOG_HOME/errors.log
MODULE_PID=/run/$MODULE_NAME.pid
MODULE_ACT=$MODULE_HOME/conf/kros.active
MODULE_JAVA_OPTIONS=

case $1 in
    start)
        echo "Starting $MODULE_NAME..." 
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            echo "$MODULE_NAME is already running"
        else
            nohup java -jar $MODULE_JAVA_OPTIONS $MODULE_HOME/$MODULE_NAME.jar --wrapper 2>> $MODULE_ERR >> $MODULE_LOG &
            echo $! > $MODULE_PID
            echo "$MODULE_NAME (pid $!) started"
        fi
    ;;
    stop)
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            PID=$(cat $MODULE_PID);
            echo "Stopping $MODULE_NAME ..."
            kill $PID;
            echo "$MODULE_NAME stopped"
            rm $MODULE_PID
            rm $MODULE_ACT
        else
            echo "$MODULE_NAME is not running"
        fi
    ;;
    restart)
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            PID=$(cat $MODULE_PID);
            echo "Stopping $MODULE_NAME ...";
            kill $PID;
            sleep 5
            echo "$MODULE_NAME stopped";
            rm $MODULE_PID
            rm $MODULE_ACT
        else
            echo "$MODULE_NAME is not running"
        fi
 
        echo "Starting $MODULE_NAME ..."
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            echo "$MODULE_NAME is already running"
        else
            nohup java -jar $MODULE_JAVA_OPTIONS $MODULE_HOME/$MODULE_NAME.jar --wrapper 2>> $MODULE_ERR >> $MODULE_LOG &
            echo $! > $MODULE_PID
            echo "$MODULE_NAME (pid $!) started"
        fi
    ;;
    status)
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            PID=$(cat $MODULE_PID);
            echo "$MODULE_NAME (pid $PID) is running...";
            java -jar $MODULE_HOME/$MODULE_NAME.jar --status
        else
            echo "$MODULE_NAME is not running ..."
        fi
    ;;
    register)
        if [ $(pgrep -F $MODULE_PID 2> /dev/nul) ]; then
            echo "$MODULE_NAME is running. Stop it.";
        else
            java -jar $MODULE_HOME/$MODULE_NAME.jar --register
        fi
    ;;
    version)
        java -jar $MODULE_HOME/$MODULE_NAME.jar --check
    ;;
    news)
        java -jar $MODULE_HOME/$MODULE_NAME.jar --news
    ;;
    upgrade)
        java -jar $MODULE_HOME/$MODULE_NAME.jar --upgrade
    ;;
esac

