#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          etherpad
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: etherpad sysv init script
# Description:       collaborative text editor
### END INIT INFO
#

export HOME=/root/

# repertoire d'installation
INSTALLPATH=/usr/share/eole/nodejs/etherpad

# nom
NAME="Etherpad"

#Logfile
LOGFILE=/var/log/etherpad.log

#PM2 binary
PM2=/usr/bin/pm2

#Etherpad config
EP_CONF=/etc/pm2/etherpad.json

# fihchier de log
PIDFILE=/var/run/etherpad.pid


#Move to the folder where ep-lite is installed
cd $INSTALLPATH

# si node.js n'est pas executable on sort silencieusement
test -x $NODE || exit 0

# chargement des fonctions
. /lib/lsb/init-functions


# fonction d'initialisation
ep_init () {
    #prepare the enviroment
    cd $INSTALLPATH
    ./eoleDeps.sh $* 2>/dev/null || exit 1
}

# fonction de demarrage
ep_start () {
    log_daemon_msg "Starting $NAME"
    HOME=/root ${PM2} start ${EP_CONF}
    log_end_msg $?
    return $?
}

# fonction d'arret
ep_stop () {
    log_daemon_msg "Stopping $NAME"
    ret=$?
    HOME=/root ${PM2} stop ${EP_CONF}
    if [ $ret -eq 0 ]
    then
        log_end_msg $ret
    fi
    return $ret
}

# fonction de status
ep_status () {
    HOME=/root ${PM2} show ${EP_CONF}
}


case "$1" in
  start)
     ep_init && ep_start || exit 0
     #ep_start || exit 1
     ;;
  stop)
     ep_stop || exit 0
     ;;
  restart)
     ep_stop && ep_start || exit 0
     ;;
  status)
     ep_status || exit 0
     ;;
  *)
     echo "Usage: $0 {start|stop|restart|status}"
     exit 1
esac

exit 0

