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

use strict;
use Carp;
use IO::File;

sub unable {
  Carp::carp('logrange: unable to ', @_, ': ', $!);
}

if (scalar(@ARGV)<1 or scalar(@ARGV)>3) {
  warn("logrange: usage: logrange dir [start [end]]\n");
  exit(100);
}

my $dir=$ARGV[0];

my $start='@000000000000000000000000';
$start=$ARGV[1] if scalar(@ARGV)>1;
if (ord($start)==ord('@')) { $start=substr($start, 1); }
elsif (ord($start)==ord("\$")) { $start=$ENV{substr($start, 1)}; }
else {
  warn('logrange: unrecognized format: ', $start, "\n");
  exit(100);
}

my $end='@ffffffffffffffffffffffff';
$end=$ARGV[2] if scalar(@ARGV)>2;
if (ord($end)==ord('@')) { $end=substr($end, 1); }
elsif (ord($end)==ord("\$")) { $end=$ENV{substr($end, 1)}; }
else {
  warn('logrange: unrecognized format: ', $end, "\n");
  exit(100);
}

unless (opendir(DIR, $dir)) {
  unable('open ', $ARGV[0]);
  exit(100);
}
my @files=readdir(DIR);
closedir(DIR);

my $fh=IO::File->new();
my $stdout=*STDOUT{'IO'};
foreach my $file (sort(@files)) {
  if (ord($file)==ord('@')) {
    my $stamp=substr($file, 1, 24);
    next if $stamp lt $start;
    last if $stamp gt $end;
  } elsif ($file ne 'current') {
    next;
  }
  $file=$dir.'/'.$file;
  unless ($fh->open($file)) {
    unable('open ', $file);
    next;
  }
  my $line;
  while (defined($line=$fh->getline())) {
    my $stamp=substr($line, 1, 24);
    next if $stamp lt $start;
    last if $stamp gt $end;
    $stdout->print($line);
  }
}
