#!/usr/local/bin/perl -w

# this works just like "tail -f" but can be used to tail many files. You
# are required to give a prefix for each file, and this script promises
# to not print a line from a file unless it ends with a line feed (to
# minimize confusion).
#
#	tailn access /opt/JavaWebServer/logs/javawebserver/webpageservice/access_log events /opt/JavaWebServer/logs/javawebserver/webpageservice/event_log errors /opt/JavaWebServer/logs/javawebserver/webpageservice/error_log
#
########################################################################
#
# Copyright (c) 2000 Tom Howland
#
# You may distribute copies or derivations of this file under the terms
# of either the GNU General Public License or the Artistic License, as
# specified in the Perl README file.
#
# This code is provided with no warranty of any kind,and is used
# entirely at your own risk. This code was written by the author as a
# private individual, and is in no way endorsed or warrantied.
#
# Support questions and suggestions can be directed to tom@rahul.net
# Download from http://www.rahul.net/tom/WebMonitor.html
#
########################################################################

$args = @ARGV;
$pairs = $args >> 1;
$last = $pairs - 1;
$prefix[$last] = 0;
$fn[$last] = 0;
$p[$last] = 0;

$| = 1;

for($i=0; $i < $pairs; $i++){
  my $x = $i << 1;
  $prefix[$i] = $ARGV[$x];
  $f = $ARGV[$x + 1];
  $fn[$i] = $f;
  if(open($f, $f)){
    $e[$i] = $!;
    if(seek($f, -999, 2)){
      <$f>;
      $p[$i] = tell($f);
    } else {
      $p[$i] = 0;
      seek($f, 0, 0);
    }
    $bogus[$i] = 0;
  } else {
    $e[$i] = $!;
    print "!: $f : $!\n";
    $bogus[$i] = 1;
  }
}

while(1){
  for($i=0; $i < $pairs; $i++){
    $f = $fn[$i];

    # maybe the log file was cycled

    my $size = -s $f;

    if(defined($size)){

      if($bogus[$i] || $size < $p[$i]){
	if(open($f, $f)){
	  $p[$i] = 0;
	  $bogus[$i] = 0;
	} else {
	  $bogus[$i] = 1;
	  if($! != $e[$i]){
	    $e[$i] = $!;
	    print "!: $f : $!\n";
	  }
	  next;
	}
      }

      while(<$f>){
	if(/\n$/){
	  print $prefix[$i], ': ', $_;
	  $p[$i] = tell($f);
	}
      }
      seek($f, $p[$i], 0);
    }
  }
  sleep 1;
}
