#!/bin/sh

CONF_FILE="/etc/mosquitto/conf.d/barix.conf"
USERNAME="mqttuser"
PASSWORD=$(openssl rand -base64 16)
PASSWD_FILE="/tmp/mqtt/passwd"
TMP_PASSWD_FILE="/tmp/mqtt/credentials.json"


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

write_listeners() {
    : > "$CONF_FILE"
    # Keep the local metrics publisher's anonymous access separate from the
    # authenticated WebSocket listener.
    echo "per_listener_settings true" >> "$CONF_FILE"

    sections=$(uci -q show mqtt | sed -n "s/^mqtt\.\([^=]*\)=listener$/\1/p")

    if [ -z "$sections" ]; then
        echo "No MQTT listeners configured"
        return 1
    fi

    for section in $sections; do
        port=$(uci -q get "mqtt.${section}.port")
        protocol=$(uci -q get "mqtt.${section}.protocol")
        password=$(uci -q get "mqtt.${section}.password")
        anonymous=$(uci -q get "mqtt.${section}.anonymous")

        if [ -z "$port" ]; then
            echo "Missing MQTT listener port for section '${section}'"
            return 1
        fi

        if [ -z "$protocol" ]; then
            echo "Missing MQTT listener protocol for section '${section}'"
            return 1
        fi

        if [ -z "$anonymous" ]; then
            echo "Missing MQTT listener anonymous for section '${section}'"
            return 1
        fi


        {
            # Anonymous access is only for on-device publishers. Apply this to
            # saved configurations too, which may predate this restriction.
            if [ "$anonymous" = "true" ]; then
                echo "listener ${port} 127.0.0.1"
            else
                echo "listener ${port}"
            fi
            echo "protocol ${protocol}"
            echo "allow_anonymous ${anonymous}"
            if [ "$password" = "true" ]; then
                echo "password_file ${PASSWD_FILE}"
            fi
            echo
        } >> "$CONF_FILE"
    done
}

start() {

    create_config

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

    if [ "$enabled" != "true" ]; then
        echo "MQTT is disabled"
        exit 1
    fi

    if [ ! -f $TMP_PASSWD_FILE ] || [ ! -f $PASSWD_FILE ]; then
        mkdir -p /tmp/mqtt
        mosquitto_passwd -c -b $PASSWD_FILE $USERNAME $PASSWORD

        # Ensure correct permissions
        chown mosquitto:mosquitto $PASSWD_FILE
        chmod 600 $PASSWD_FILE

        # Set environment variables for the current session TODO change this for a json
        echo '{"username": "'"$USERNAME"'", "password": "'"$PASSWORD"'"}' | jq '.' > "$TMP_PASSWD_FILE"
    fi

    write_listeners

    if [ ! -s "$CONF_FILE" ]; then
        echo "No MQTT listeners configured"
        exit 1
    fi

    /etc/init.d/mosquitto start
}


stop() {
    /etc/init.d/mosquitto stop
}


restart() {
    stop
    start
}

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