#!/bin/sh
# Converts a uci config file into an appropriate mosquitto.conf snippet
# expected to be used in an init file to generate a config file to run from
# Karl Palsson <karlp@remake.is> 2012.
# Considered to be released into the public domain

TCONF=/tmp/mosquitto.generated.$$.conf
while getopts "f:" o; do
    case $o in
    f)
        TCONF=$OPTARG
        ;;
    esac
done

if [ -e $TCONF ]; then
    echo "Odd, same temporary generated config file already existed: $TCONF"
    exit 1
fi

echo "Generating mosquitto config file in $TCONF"
NOW=$(date)
echo "# mosquitto.conf file generated from UCI config." >>$TCONF
echo "# Config snippet generated by $0 on $NOW" >>$TCONF
echo "#" >> $TCONF
QQ=$(uci -q get mosquitto.mosquitto.log_dest)
if [ $? = 0 ]; then
    for dest in $QQ; do
        echo "log_dest $dest" >> $TCONF
    done
fi

QQ=$(uci -q get mosquitto.mosquitto.no_remote_access)
if [ $? = 0 ]; then
    if [ "$QQ" -eq 1 ]; then
        echo "bind_address 127.0.0.1" >> $TCONF
    fi
fi

HATE_SECTION_COUNT=$(grep config /etc/config/mosquitto | grep bridge | wc -l)
if [ $HATE_SECTION_COUNT -gt 0 ]; then
    for i in $(seq $HATE_SECTION_COUNT -1 1); do
        NN=$(uci -q get mosquitto.@bridge[-$i].connection)
        echo "" >> $TCONF
        echo "# Bridge connection from UCI section" >> $TCONF
        echo "connection $NN" >> $TCONF
        ADDR=$(uci -q get mosquitto.@bridge[-$i].address)
        echo "address $ADDR" >> $TCONF
        TOPICS=$(uci -q -d';' get mosquitto.@bridge[-$i].topic)
        # UGLY! just want to split on the ; :(
        echo $TOPICS | sed "s/^/topic /" | sed "s/;/\ntopic /g" >> $TCONF
        CS=$(uci -q get mosquitto.@bridge[-$i].cleansession)
        if [ $? -eq 0 ]; then
            if [ "$CS" -eq 1 ]; then
                echo "cleansession true" >> $TCONF
            fi
        else
            echo "cleansession false" >> $TCONF
        fi
        TRYPRIV=$(uci -q get mosquitto.@bridge[-$i].tryprivate)
        if [ $? -eq 0 ]; then
            if [ "$TRYPRIV" -eq 1 ]; then
                echo "try_private true" >> $TCONF
            else
                echo "try_private false" >> $TCONF
            fi
        else
            # Override default to avoid crashes with 0.15 brokers :(
            echo "try_private false" >> $TCONF
        fi
        CLIENTID=$(uci -q get mosquitto.@bridge[-$i].clientid)
        if [ $? -eq 0 ]; then
            echo "clientid $CLIENTID" >> $TCONF
        fi
        BRIDGEID=$(uci -q get mosquitto.@bridge[-$i].identity)
        if [ $? -eq 0 ]; then
            echo "bridge_identity $BRIDGEID" >> $TCONF
        fi
        BRIDGEPSK=$(uci -q get mosquitto.@bridge[-$i].psk)
        if [ $? -eq 0 ]; then
            echo "bridge_psk $BRIDGEPSK" >> $TCONF
        fi
        BRIDGETLSVERSION=$(uci -q get mosquitto.@bridge[-$i].tls_version)
        if [ $? -eq 0 ]; then
            echo "bridge_tls_version $BRIDGETLSVERSION" >> $TCONF
        fi
    done
fi
