#!/bin/bash
set -e

#==========================================
#            HELPER FUNCTIONS
#==========================================
function_log(){
    MSG=$1
    echo -e "${YELLOW}${MSG}${NC}"
    logger -t "configure-10serie$" $1
}

function_replace_line_in_file(){
    STRING_TO_FIND=$1
    NEW_LINE=$2
    FILE_NAME=$3
    sed -i "s/$STRING_TO_FIND/$NEW_LINE/" "$FILE_NAME"
}

function_insert_line_if_not_found(){
    LINE=$1
    CONF_FILE=$2
    AFTER=$3
    grep -qxF "$LINE" "$CONF_FILE" || sed -i "/$AFTER/a\\"$LINE $CONF_FILE
}



# 10 Trace firewall settings
REGEX_NUMBER='^[0-9]+$'
DCS_PORT=$(xmlstarlet sel -t -v "/root/Ethernet/Port" /opt/satisloh/10trace/setup/commPreferences.xml)
if [[ $DCS_PORT =~ $REGEX_NUMBER ]]; then
    function_replace_line_in_file "ports=.*" "ports=33511\/udp|$DCS_PORT\/tcp" "/etc/ufw/applications.d/10serie"
fi

/usr/sbin/ufw allow '10 Serie'

if dpkg -s "10trace-os-customization-dev" ; then
    ufw --force disable
else
    ufw --force enable
fi