#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell
package PrintKML;
use strict;
use File::stat;
use Getopt::Long;
use POSIX qw(:sys_stat_h :errno_h :unistd_h :fcntl_h);
use IO::File;

use lib qw(/usr/lib/intermezzo /usr/lib/intermezzo/i386-linux);

use Lento::KML;
use Lento::KML::Rec;

=pod

=head1  NAME

kml-print - show records in the KML file

=head1  SYNOPSIS

kml-print [--debuglevel=level] [--brief] [--kml_offset=bytes] [--pattern=string]  cache-mount-point fileset-name

=head1  DESCRIPTION

Print records from the KML file for the fileset passed on the command line which should be part of the InterMezzo cache mounted on the cache-mount-point.

=head1 Arguments

Command line arguments:

=over 4

=item B<cache-mount-point> Directory of the InterMezzo file system
mountpoint. 

=item B<filesetname> Name of the fileset as given in /etc/intermezzo/fsetdb.

=back

=cut

$PrintKML::level=0;
$Lento::KML::Rec::level = 0;

$::global_debug=-1000;
my $brief;
my $verybrief;
my $briefly;
my $pattern;
my $kml_offset = 0;
my $chkpattern = 0;

sub printusage {

    print "Usage kml-print.pl cache-mount-point file-set-name [--brief] [--pattern=string] [--kml_offset=bytes] [--debuglevel=level]\n";
    exit(1);
}

if (!GetOptions("brief!" => \$brief, 
		"verybrief!" => \$verybrief,
                "pattern=s" => \$pattern,
                "kml_offset=i" => \$kml_offset) ) {
     printusage();
}

if ($brief) {
   $briefly = "brief";
}
if ($verybrief) {
   $briefly = "verybrief";
}

my $mountpoint = shift @ARGV;
my $fsetname = shift @ARGV;

die printusage() if !defined $mountpoint;
die printusage() if !defined $fsetname;

my $result = "";
my $count = 0;

if ((defined $pattern) && (length($pattern) > 0)) {
    $chkpattern = 1;
}

my $kml = Lento::KML->new($mountpoint . "/.intermezzo/" . $fsetname . "/kml");

my $kml_st = stat($mountpoint . "/.intermezzo/" . $fsetname . "/kml") || die;

$kml->last_offset($kml_st->size);

my $count = 0;
my $slot_offset = 0;

while ($kml_offset < $kml->last_offset() ) {
    my ($size, $offset, $buf) = $kml->readrec($kml_offset);
    last if $size == 0;

    print "found and skipped chunk boundary\n" if ($offset > $kml_offset);

    my $rec = Lento::KML::Rec->Unpack($buf, 0, $kml_offset);

    $kml_offset = $offset + $size;
    $count++;
    my $printstr;

    $printstr .= sprintf("Record $count size: $size, start off $offset, end off $kml_offset, (log length %d)\n", $kml_st->size);
    
    $printstr .= $rec->printme($briefly);

    if ($chkpattern) {
	if ($printstr =~ m/$pattern/) {
	    if (!$briefly) {
		print "----------------------------------------------------------------\n";
	    }
	    print $printstr;
	}
    } else {
	
	if (!$briefly) {
	    print "----------------------------------------------------------------\n";
	}
	print $printstr;
    }
}


