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

if [ -e /etc/init/rsyslog.conf ] ; then
    # 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
    initctl stop rsyslog 2>/dev/null
    [ "${SYSLOG_HOST}" != "0.0.0.0" ] && initctl start rsyslog

else
    # Running old syslog
    if [ "${reset}" = "1" ] ; then
	if test "${SYSLOG_HOST}" = "local" -o "${SYSLOG_HOST}" = "0.0.0.0"; then
            echo "*.*   /dev/null" >  /etc/syslog.conf
	    sed -i -e "s:\(^syslog[^0-9]*\).*\(/udp.*\):\1514\2:" /etc/services
	else
            echo "*.*   @${SYSLOG_HOST}" >  /etc/syslog.conf
            sed -i -e "s:\(^syslog[^0-9]*\).*\(/udp.*\):\1${SYSLOG_PORT}\2:" /etc/services
	fi
    else
	ipaddr=${1%:*}
	port=${1#*:}
	if [ "${ipaddr}" != "${port}" ] ; then
	    # Port given
	    sed -i -e "s:\(^syslog[^0-9]*\).*\(/udp.*\):\1${port}\2:" /etc/services
	fi

	echo "*.* @${ipaddr}" > /etc/syslog.conf
    fi
    /etc/init.d/sysklogd stop
    [ "${SYSLOG_HOST}" != "0.0.0.0" ] && /etc/init.d/sysklogd start
fi


exit 0
