#!/bin/sh

# This stuff will be ignored by systems that don't use chkconfig.
# chkconfig: 345 98 13
# description: scheduler-portal

# config:

### BEGIN INIT INFO
# Provides:         easy-scheduler
# Required-Start:
# Required-Stop:
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: EasyScheduler
# Description:       EasyScheduler service
### END INIT INFO

# Starts and stops the EasyScheduler

# Some general variables

HOME=/opt/easyportal/scheduler
VERSION=*

JAVA_HOME=/usr/lib/jvm/jre-17-openjdk

# starts EasyScheduler
start () {
     if [ ! -z "$(ps ax | grep -v grep | grep java | grep scheduler-${VERSION}.jar | awk ' {print $1}')" ] ; then
        echo "EasyScheduler service is still running"
        exit 1
     fi
        cd ${HOME}
        sudo -E -u easyportal bash -c "nohup $JAVA_HOME/bin/java -Xmx2g -jar scheduler-${VERSION}.jar > ./log/start.log 2>&1 &"
        touch /var/lock/subsys/easy-scheduler
}

# stops scheduler-portal
stop () {
if [ ! -z "$(ps ax | grep -v grep | grep java | grep scheduler-${VERSION}.jar | awk ' {print $1}')" ] ; then
         PID=$(ps ax | grep -v grep | grep java | grep scheduler-${VERSION}.jar | awk ' {print $1}')
         kill -TERM ${PID}
         echo SIGTERM sent to process ${PID}
         rm /var/lock/subsys/easy-scheduler
     else
         echo Process EasyScheduler not found!
     fi
}

case "$1" in
    init)
      start
      ;;
    start)
      start
      ;;
    stop)
      stop
      ;;
    zap)
     stop
      ;;
    restart)
      stop
      sleep 5
      start
      ;;
    *)
        echo "Usage: /etc/init.d/easy-scheduler {start|stop}"
        exit 1
        ;;
esac

exit 0

