#!/bin/bash
# Call: oxs-xxx-server start|stop|restart 
if [ "$1" == "" ] 
then
   echo $"Usage: $0 {start|stop|restart}"
   exit 1
fi

# Set the Environment Variables contained in /etc/environment (i.e. DMS2_)
set -o allexport
. /etc/environment
set +o allexport

# OXS_SERVER_CONFDIR is optional, default value is /usr/lib/node_modules/<server name>. If defined, it MUST be in /etc/environment
# OXS_PROCESSES_CONFIG_JS should be defined in /etc/environment
if [ "$OXS_PROCESSES_CONFIG_JS" = "" ]; then
    OXS_PROCESSES_CONFIG_JS=processes.config.js
fi

if [ "$OXS_SERVER_CONFDIR" = "" ]; then
    OXS_SERVER_CONFDIR=/usr/lib/node_modules
fi

processes_json=$OXS_SERVER_CONFDIR/${0##*/}/conf/${0##*/}/$OXS_PROCESSES_CONFIG_JS

echo "Running $processes_json ..."

stop () {
    pm2 delete $processes_json
    pm2 save --force
}

status () {
    pm2 desc ${0##*/}
}

start () {
    pm2 startOrRestart $processes_json
    pm2 save --force
}

case "$1" in
        start)
            start
            ;;

        stop)
            stop
            ;;

        status)
            status
            ;;
        restart)
            stop
            sleep 5
            start
            ;;
        *)
            echo $"Usage: $0 {start|stop|restart}"
            exit 1
esac
