#!/bin/bash

# Check if user exits
USER=mqttnetsrv
USEREXISTS=$(id -u $USER >/dev/null 2>&1; echo $?)
EC=0
BASEPATH=/opt
INSTALLPATH=$BASEPATH/MQTTnetServer

# If user does not exist, create it
if (( $USEREXISTS == 1 )); then
        useradd -d $INSTALLPATH -m -r $USER
        EC=$(echo $?)

        if (( $EC == 1 )); then
                exit 1;
        fi
fi

# Set permissions on files
chown -R root:root $INSTALLPATH

# Check if config does not exist and create it
if [ ! -f "$INSTALLPATH/appsettings.json" ]; then
    cp $INSTALLPATH/appsettings.template.json $INSTALLPATH/appsettings.json
fi

# Enable MQTTServer.NET to bind to IP interface
setcap CAP_NET_BIND_SERVICE=+eip $INSTALLPATH/MQTTnet.Server

chmod 644 /etc/systemd/system/mqttnet-server.service

# Reload systemd because of new service file
systemctl daemon-reload