#!/usr/bin/perl
$|=1;

###
# Configuration variables
#
use constant DEBUG => 1; # Print those debugging messages
use constant DELAY => 1; # Amount of time to sleep between checks
use constant ATEND => 1; # Start at the end of the file contents?
#
# End configuration
###

use POSIX; # get those handy system constants

$file = $ARGV[0];
open(FILE,"<$file") || die("Failed to open $file\n");

seek(FILE, 0, SEEK_END) if ATEND;

for(;;) {
  while (($_ = <FILE>)) {
    # Process line
    chomp;
    print "Got: $_\n" if DEBUG;
  }
  $curpos = tell(FILE); 
  seek(FILE, $curpos, SEEK_SET);

  (@cstat = stat FILE) || die ("fstat failed");
  (@nstat = stat $file) || die ("stat $file failed");

  $newfile = 0;
  # File size reset ?
  $newfile = 1 if ($curpos > $cstat[7]);
  # File on a new device ?
  $newfile = 1 if ($cstat[0] != $nstat[0]);
  # File on a new inode ?
  $newfile = 1 if ($cstat[1] != $nstat[1]);
  
  if ($newfile) {
    print "Switching to new $file\n" if DEBUG;
    close(FILE);
    open(FILE,"<$file") || die("Failed to open $file\n");
  } else {
    sleep DELAY;
  }
}

