#!/bin/bash

TODAY=$(date "+%Y%m%d")
PYTHON_EXEC=${HOME}/dust-dashboard/bin/
DASH_HOME=${HOME}/interactive-forecast-viewer
LOGDIR=${DASH_HOME}/log/gunicorn/
LOGLEV=error
CONNECTIONS=20
MOD="eventlet"
WORKERS=7
PORT=9000
HOST='0.0.0.0'  # `hostname -f`

function stop_app {
	echo -n "Shutting down current service ... "
	kill `ps auxww | grep $PORT | grep gunicorn | awk '{ printf $2" "}'`
	wait
	echo "done."
}

function start_app {
	echo -n "Starting new service with class $MOD and workers $WORKERS ... "
	cd $DASH_HOME
	${PYTHON_EXEC}/gunicorn \
	    --access-logfile ${LOGDIR}/${TODAY}.access.log \
	    --error-logfile ${LOGDIR}/${TODAY}.error.log \
	    --pid /run/interactive-forecast-viewer/interactive-forecast-viewer.pid \
	    --capture-output --log-level $LOGLEV \
	    -w $WORKERS --preload \
	    --worker-class=$MOD \
	    --worker-connections=$CONNECTIONS \
	    -b $HOST:$PORT \
	    dash_server:server -D
	wait
	echo "done".
	#    --max-requests 100 \
	#    --max-requests-jitter 10 \
	#        --threads `expr $workers - 1` \
	#    --timeout=30 \
}

case "$1" in
    start)   start_app ;;
    stop)    stop_app ;;
    restart) stop_app; start_app ;;
    *) echo "usage: $0 start|stop|restart" >&2
       exit 1
       ;;
esac
