#!/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  -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


# Check if setcap exists, does not exist in docker containers
SCAP=$(which setcap >/dev/null; echo $?)
if [ "$SCAP" -eq "0" ]; then
    # Enable MQTTServer.NET to bind to IP interface
    setcap CAP_NET_BIND_SERVICE=+eip $INSTALLPATH/MQTTnet.Server
fi

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

# Check if systemctl exists, does not exist in docker containers
SCTL=$(which systemctl >/dev/null; echo $?)

if [ "$SCTL" -eq "0" ]; then
    # Reload systemd because of new service file
    systemctl daemon-reload
fi