#!/bin/sh
#
# Hack that redirects multiple chrooted /dev/logs to the system /dev/log to be picked up
# by HP-UX's stock syslogd which doesn't support multiple fifos.
#
# The latest version can be found at:
# http://www.mayoxide.com/toolbox
#
# (c) 2008 Olivier S. Masse, omasse ~at~ mayoxide ~dot~ com
#
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#

pidfile=/var/run/log_redirector.pids

function redirect
{
	cd $(dirname $1) 
	while true
	do
		cat $1 >/dev/log
	done
}

# Bring up a usage if no options
if [ "$1" = "" ]
then
	echo "Usage: $(basename $0) chrooted_dev_log ..."
	echo "	     $(basename $0) stop"
	exit 1
fi

# Kill children if "stop" option is given
if [ "$1" = "stop" ]
then
	if [ ! -f ${pidfile} ]
	then
		echo "Pidfile '${pidfile}' is missing, exit."
		exit 1
	fi
	
	for pid in $(cat ${pidfile})
	do
		# each child "cat" must be killed independently, else it stays there waiting until
		# something comes in the pipe
		children=$(UNIX95=1 ps -o ppid,pid | awk -v ppid=${pid} '{if ($1 == ppid) print $2}')
		echo "Killing pid ${pid}"
		kill ${pid}
		
		# the children are killed AFTER their parents since new ones start instantly
		# if we kill them before. 
		for child in ${children}
		do	
			echo "Killing pid ${child} (former child of ${pid})"
			kill ${child}
		done
	done
	rm ${pidfile}
	exit 0
fi

# Refuse to start is already running
if [ -f ${pidfile} ]
then
	echo "${pidfile} is present, please run me with 'stop' first."
	exit 0
fi

# Loop through all the fifos given on the command-line, and redirect them
# in the background.
while [ "$1" ]
do
	if [ ! -p $1 ]
	then
		echo "'$1' is either missing or not a FIFO, skipping."
	else
		echo "$(basename $0): redirecting $1 to /dev/log"
		redirect $1 &
		echo ${!} >>${pidfile}
	fi
	shift
done

exit 0


