#!/bin/bash

###########################################################################
#
# MODULE:       Scripts
# AUTHOR(S):    CacheGuard Development Team
# COPYRIGHT:    (C) 2009-2025 by CacheGuard Technologies Ltd (UK)
# COPYRIGHT:    (C) 2026-2026 by CacheGuard Technologies SAS (FR)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###########################################################################

CACHEGUARD_DIR=/etc/sysconfig/cacheguard
source ${CACHEGUARD_DIR}/constant
source ${APPLIANCE_DIR}/etc/role

[ ! -f /etc/sysconfig/rlogger ] || source /etc/sysconfig/rlogger

send-to-syslog_servers()
{
    test -n "${1}" || return 0
    local message=${1}

    test -n "${SYSLOG_SERVERS}" || return 0

    local protocol_server_port server_port
    local protocol server port
    local tag='guard'

    for protocol_server_port in ${SYSLOG_SERVERS}
    do
	protocol=--${protocol_server_port/:*}
	server_port=${protocol_server_port#*:}
	server=${server_port/:*}
	port=${server_port/*:}

	logger \
	    --server ${server} ${protocol} --port ${port} \
	    --priority syslog.alert --tag ${tag} \
	    -- ${message} > /dev/null 2>&1
    done
}

main()
{
    test -n "${1}" || return 1
    local log_file_in=${1}
    local log_file_out=${2}
    local log_remote=${3}

    local date code message

    if test -n "${log_file_out}" ; then
	test -p ${log_file_in} || return 11
	test -n "${log_remote}" || log_remote='no'
	while true
	do
	    read date code message < ${log_file_in}
	    echo ${date} ${code} ${message} >> ${log_file_out}
	    test ${log_remote} == 'no' || send-to-syslog_servers "${message}"
	done
    else
	test -f ${log_file_in} || return 13
	tail --follow --lines=0 ${log_file_in} | \
	    while read date code message
	    do
		send-to-syslog_servers "${message}"
	    done
    fi
}

# Main()

main "${@}"
