#!/bin/bash
# Set host for forwarding syslog messages
# Call: switchsyslog [ip-address[:port]]
# Calling without parameter resets according to entry in config.lua

reset=0

if [ -z "$1" ] ; then
    reset=1
    if test -f /data/config.lua ; then
        if grep -q string_SyslogDestination /data/config.lua; then
            SYSLOG_HOST=$(grep string_SyslogDestination /data/config.lua | sed -e "s/.*\"\(.*\)\".*/\\1/")
            SYSLOG_PORT=$(grep string_SyslogPort /data/config.lua | sed -e "s/.*\"\(.*\)\".*/\\1/")
            SYSLOG_PROTOCOL=$(grep string_SyslogProtocol /data/config.lua | sed -e "s/.*\"\(.*\)\".*/\\1/")
        else
            SYSLOG_HOST="local"
        fi
    fi    
    if [ -z "${SYSLOG_PORT}" ] ; then
        SYSLOG_PORT="514"
    fi
fi

# Running rsyslogd
if [ "${reset}" = "1" ] ; then
    echo '$template ferrariFormat,"<%PRI%>%timereported:1:10:date-rfc3339% %timereported:12:22:date-rfc3339% %HOSTNAME%%msg%\n"' > /etc/rsyslog.d/50-default.conf

    if test "${SYSLOG_HOST}" = "0.0.0.0"; then
        echo "*.*   /dev/null" >> /etc/rsyslog.d/50-default.conf  
    elif test "${SYSLOG_HOST}" = "local"; then
        echo "*.*   /var/log/syslog;ferrariFormat" >> /etc/rsyslog.d/50-default.conf  
    else
        if [ "${SYSLOG_PROTOCOL}" = "tcp" ]; then
            echo "*.*   @@${SYSLOG_HOST}:${SYSLOG_PORT};ferrariFormat" >>  /etc/rsyslog.d/50-default.conf
        else
            echo "*.*   @${SYSLOG_HOST}:${SYSLOG_PORT};ferrariFormat" >>  /etc/rsyslog.d/50-default.conf
        fi
    fi

else
    echo "*.* @${1}" > /etc/rsyslog.d/50-default.conf
fi

OS=$(omgsysteminfo --filter="os.name" --val)
if [ "${OS}" = "ubuntu" ]; then
    initctl stop rsyslog 2>/dev/null
    initctl start rsyslog 2>/dev/null
else
    service rsyslog restart
fi

exit 0
