#!/bin/sh
# flexa-app start-up script.
APP_NAME="flexa-agent"
APP_PID_FILE="/var/run/${APP_NAME}.pid"

migrate_config() {
    if [ -z "$(uci -q get flexa_agent.application)" ]; then
        uci -q set flexa_agent.application='section'
        uci commit flexa_agent
    fi

    if [ -z "$(uci -q get flexa_agent.service.enabled)" ]; then
        value=$(uci -q -c /barix/config/defaults/ get flexa_agent.service.enabled)
        uci -q set flexa_agent.service.enabled="$value"
        uci commit flexa_agent
    fi

    if [ -z "$(uci -q get flexa_agent.service.enable_usb_update)" ]; then
        value=$(uci -q -c /barix/config/defaults/ get flexa_agent.service.enable_usb_update)
        uci -q set flexa_agent.service.enable_usb_update="$value"
        uci commit flexa_agent
    fi
}

start() {
    migrate_config

    echo "${APP_NAME}: Starting the ${APP_NAME} application..."
    $APP_NAME &
    echo "${APP_NAME}: Starting the ${APP_NAME} application...DONE"
}

stop() {
    echo "${APP_NAME}: Stopping the ${APP_NAME} application..."
    kill ${APP_PID_FILE}
    rm -f ${APP_PID_FILE}
    echo "${APP_NAME}: Stopping the ${APP_NAME} application...DONE"
}

restart() {
    stop
    start
}

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