#!/bin/bash

### BEGIN INIT INFO
# Provides:          sparkleshare-dashboard
# Required-Start:    $local_fs $remote_fs $network $all
# Required-Stop:     $local_fs $remote_fs $network 
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop Sparkleshare-Dashboard
### END INIT INFO

USER=sparkledash
NAME=sparkleshare-dashboard
SCRIPTNAME=sparkleshare-dashboard
PID_FILE=/var/run/sparkleshare-dashboard.pid
LOGFILE=/var/log/sparkleshare-dash.log

[ ! -e ${LOGFILE} ] && {
    touch ${LOGFILE}
    chown ${USER} ${LOGFILE}
}

do_start()
{
	if [ -f $PID_FILE ]; then
	   echo "$NAME is already running!"
	   	exit 1
		fi
		echo "Starting $NAME..."
		## ggf. anpassen! Pfad zu den Dashboard-Dateien
		cd /usr/local/src/sparkleshare-dashboard
		su -c 'NODE_ENV=production node app.js' $USER &> ${LOGFILE} &
		echo $! > $PID_FILE
		sleep 1
}

do_stop()
{
	if [ ! -f $PID_FILE ]; then
	   echo "$NAME does not seem to be running!"
	   	exit 1
		fi
		kill `cat $PID_FILE` &> /dev/null
		echo -n "Stopping $NAME..."
		sleep 5
		kill -9 `cat $PID_FILE` &> /dev/null
		rm $PID_FILE &> /dev/null
}

case "$1" in
  start)
        do_start
	exit 0
        ;;
  stop)
        do_stop
	exit 0
        ;;
  restart)
	do_stop
	sleep 5
	do_start
	exit 0
	;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop}" >&2
        exit 3
        ;;
esac
