#!/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: forever 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
#

#switch to another user
if [ $UID -eq 0 ]; then
  exec su "ctrack" "$0" "$@"
fi

command="/usr/bin/node"
nodeDir="/home/ctrack/D-Portal"
nodeApp="$nodeDir/dportal/js/serv.js"
foreverApp="/usr/local/bin/forever"

logDir="$nodeDir/dportal/production"
logFile="$logDir/dportal-instance"

start() {
	echo "Starting $nodeApp"


	# Notice that we change the PATH because on reboot
   # the PATH does not include the path to node.
   # Launching forever with a full path
   # does not work unless we set the PATH.
   PATH=/usr/local/bin:$PATH
#   source $nodeDir/bin/server/env.sh
   export NODE_ENV=production
   export DSTORE_INSTANCE="instance"
#   export DSTORE_DEBUG=1
   cd $nodeDir/dportal/production
   $foreverApp start -p ${logDir} --pidFile ${logFile}.pid -l ${logFile}.log -e ${logFile}.err -o ${logFile}.out -a -d -c "$command" $nodeApp
   RETVAL=$?
}

restart() {
	echo "Restarting $nodeApp"
   cd $nodeDir/dportal/production
	$foreverApp restart -p ${logDir} $nodeApp
	RETVAL=$?
}

stop() {
	echo "Shutting down $nodeApp"
   cd $nodeDir/dportal/production
   $foreverApp stop -p ${logDir} $nodeApp
   RETVAL=$?
}

status() {
   echo "Status $nodeApp"
   cd $nodeDir/dportal/production
   $foreverApp list -p ${logDir}
   RETVAL=$?
}

log() {
   echo "tail -f $logFile"
   cd $nodeDir/dportal/production
   tail -f $logFile
   RETVAL=$?
}

cron() {
   echo "cron $nodeApp"
   cd $nodeDir
   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
