#!/usr/bin/env bash
set -ex

# используется только на бете, скрипты для управления сервисом в продакшене находятся в etc/frontend/sv/js-templater

. [% IF dev %][% beta_settings.root %][% ELSE %]/etc[% END %]/js-templater/conf.sh

NODE="/usr/bin/ynode"
LUSTER="/usr/share/report-renderer/node_modules/luster/bin/luster.js"
LUSTER_CONFIG="/usr/share/report-renderer/config.js"

d_start() {
    nohup $NODE --min_semi_space_size=64 --max_semi_space_size=64 --initial_old_space_size=1024 --max_old_space_size=4096 \
        $LUSTER \
        $LUSTER_CONFIG \
        -p $PORT \
        -a $OPS_PORT \
        -w $WORKERS_CNT \
        -l $LOGS_DIR \
        --requestBodyMaxBytes=1073741824 \
        --requests-limit=100 \
        --templates-package $ROUTES $@ < /dev/null > /dev/null 2> /dev/null &
}

d_stop() {
    _act "shutdown"
}

_is_running() {
    _act "ping"
}

_act() {
    curl -f -m 3 "http://localhost:$OPS_PORT/admin?action=$1" >/dev/null 2>&1
}

if [ ! -e $NODE ]; then
    echo "Node.js binary by \"$NODE\" is not exist or not executable"
    exit 1
fi

action="$1"
shift 1

case "$action" in
    start)
        if _is_running; then
            echo "Service already running"
            exit 0
        fi
        echo "Starting"
        d_start $@
        ;;
    stop)
        if _is_running; then
            echo "Stopping"
            d_stop
        else
            echo "Service is NOT running" >&2
        fi
        ;;
    restart)
        echo "Stopping"
        if d_stop; then
            sleep 1
        fi
        echo "Starting"
        d_start $@
        ;;
    status)
        if _is_running; then
            echo "running"
        else
            echo "not running"
        fi
        ;;
    *)
        echo "Usage: $(basename $0) {start|stop|restart|status}" >&2
        exit 1
        ;;
esac
