#!/bin/sh

APP_PID=/var/run/mqtt-metrics.pid

create_config() {
    metrics_config=$(uci -q get metrics.general)
    if [ $? -ne 0 ] || [ -z "$metrics_config" ]; then
        cp -f /barix/config/defaults/metrics /barix/config/current/
        sync
    fi
}

start() {

    create_config

    mqtt_enabled=$(uci -q get mqtt.general.enabled)

    if [ "$mqtt_enabled" != "true" ]; then
        exit 1
    fi

    barix-wd --pid-file=$APP_PID --timeout=5 --background --start -- \
        python3 /usr/bin/metrics/main.py > /dev/null 2>&1 &

}

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


# 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 $?
