#!/usr/bin/perl -w

# usage: someapp --opt1  --opt2 | flockwrite.pl /path/to/shared/filename

my $OUTFILE = shift;
my $MAXSIZE = 1024;  # size of the output buffer
my $MAXAGE = 2; # max age in seconds that the buffer is allowed to be unwritten
my $BLOB = ""; # the buffer
my $range = 100;  # 0-99  # the seed for the rng
my $last_write_time = time(); # init the var

while (<>) { # while there's still stuff coming in on STDIN
    $BLOB .= $_; # just add STDIN to $BLOB
    my $current_time = time(); # take the time
    my $age = $current_time - $last_write_time;  # calc the age since last write
    if (length($BLOB) > $MAXSIZE || $age > $MAXAGE) {
    	file_still_locked($OUTFILE);  # acquire file lock
        print OUT "$BLOB";  # using flocks.
        print STDERR "!"; # indicates writes.
        close OUT;
        $BLOB = ""; # reset 
        $last_write_time = time(); #reset
    } 
}

file_still_locked($OUTFILE);
print OUT "$BLOB"; # dump the last bits
print STDERR "+"; # note it in the STDERR
close OUT;  # close and unlock

sub file_still_locked {
   $OUTFILE = shift; # grab the filename
   my $waitcnt = 0;
   my $stillclosed = 1;
   while ($stillclosed){
      $waitcnt++;
      $stillclosed = 0;
      my $random_amt = rand($range)/100;
      sleep($random_amt);
      open OUT, ">> $OUTFILE" or $stillclosed = 1;
      if (!$stillclosed){ flock(OUT, 2); }
      else {print STDERR "w ";} # string of 'wwwwww ' to indicate waits
      if ($waitcnt > 10000) { print "Dying!!\n"; die "\n\nI've been waiting too long! Dying.....\n\n"}
    }
}

