#!/bin/sh

PID_FILE="/var/run/sdf-backend.pid"

create_config() {
    sdf_config=$(uci -q get sdf.general)
    if [ $? -ne 0 ] || [ -z $sdf_config ]; then
        cp -f /barix/config/defaults/sdf /barix/config/current/
        sync
        # Need to restart lighttpd because the SDF port is proxied by lighttp
        /etc/init.d/lighttpd restart
    fi
}

start() {
    create_config

    enabled=$(uci -q get sdf.general.enabled)
    if [ "${enabled}" != "true" ]; then
        echo "SDF is disabled"
        exit 1
    fi

    sdf_port=$(uci -q get sdf.general.listening_port)

    sdf_file=$(uci -q get sdf.general.sdf_file)
    if [ ! -f "${sdf_file}" ]; then
        echo "SDF file not found"
        exit 1
    fi

    app_config=$(uci -q get sdf.general.app_config)

    SDF_LOG_PATH="/var/log/" SDF_PORT="${sdf_port}" SDF_FILE="${sdf_file}" SDF_CONFIG="${app_config}" \
    barix-wd --start --pid-file="${PID_FILE}" --background -- \
    gunicorn -b 0.0.0.0:${sdf_port} -w 1 --threads 4 --chdir=/barix/apps/sdf-engine server:app
}

stop() {
    barix-wd --stop --wait --pid-file="${PID_FILE}"
}

# See how we were called.
case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        stop
        start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
