#!/usr/bin/perl

# Copyright (C) 2010 Andrea Martire
# 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., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

use Symbol;
use IPC::Open2;

die "Error: insert at least a file descriptor" if ( @ARGV < 2 );

qx{ touch /etc/aLid/run.info };
open INFO, ">>/etc/aLid/run.info";
print INFO "$$\n";

#	Execute script 
#print "TAIL FILE = $ARGV[0].\n";
#open LOGFILE, "tail --sleep-interval=0 -f $ARGV[0] |" || die "Error Opening the file: $ARGV[0]\n";

$pid = open2(LOGFILE, CHLD_IN, "tail --sleep-interval=0 -F $ARGV[0]");

print INFO "$pid\n";
close INFO;

for $i ( 1 .. (@ARGV-1) ) {
	$ARGV[$i] =~ s/\\\?/ /g;
	$ARGV[$i] =~ s/\\/\\\\/g;
	#print "EXEC = $ARGV[$i]\n";
	#print "$indexWriter execute Script $ARGV[$i]\n";
	$writer = Symbol::gensym;
	open( $writer, "| $ARGV[$i] ");
	$list[$indexWriter++] = $writer;
	#print "$writer\n";
}

while ( <LOGFILE> ) {
	#print STDERR "read:$_";
	foreach $w( @list ) {
		print $w $_;
		#print "$w $_";
	}
}
