#!/bin/bash
### BEGIN INIT INFO
# If you wish the Daemon to be lauched at boot / stopped at shutdown :
#
#    On Debian-based distributions:
#      INSTALL : update-rc.d scriptname defaults
#      (UNINSTALL : update-rc.d -f  scriptname remove)
#
#    On RedHat-based distributions (CentOS, OpenSUSE...):
#      INSTALL : chkconfig --level 35 scriptname on
#      (UNINSTALL : chkconfig --level 35 scriptname off)
#
# chkconfig:         2345 90 60
# Provides:          dportal
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: pm2 running dportal
# Description:       dportal
### END INIT INFO
#
# initd a node app
# Based on a script posted by https://gist.github.com/jinze at https://gist.github.com/3748766
#


DIR="/dportal"
APP="$DIR/dportal/js/serv.wrap.js"
LOGFILE="$DIR/logs/dportal"




source $DIR/box/env.sh


# switch from root to $PGUSER

if [ $UID -eq 0 ]; then
	exec su "$PGUSER" "$0" "$@"
fi



start() {
	echo "Starting $APP"

	PATH=/usr/local/bin:$PATH
	cd $DIR
	. ./nvm-install
	pm2 start $APP --log ${LOGFILE}.log
	RETVAL=$?
}

restart() {
	echo "Restarting $APP"
	cd $DIR
	. ./nvm-install
	pm2 restart $APP
	RETVAL=$?
}

stop() {
	echo "Shutting down $APP"
	cd $DIR
	. ./nvm-install
	pm2 stop $APP
	RETVAL=$?
}

status() {
	echo "Status $APP"
	cd $DIR
	. ./nvm-install
	pm2 list
	RETVAL=$?
}

log() {
	echo "tail -f ${LOGFILE}"
	cd $DIR
	. ./nvm-install
	tail -f ${LOGFILE}.log
	RETVAL=$?
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status
		;;
	restart)
		restart
		;;
	log)
		log
		;;
	cron)
		cron
		;;
	*)
		echo "Usage:  {start|stop|status|restart|log}"
		exit 1
		;;
esac
exit $RETVAL
