#! /usr/bin/perl -w

# vim:syntax=perl

use strict;

use lib '/usr/local/share/perl5';

use Lire::Config;
use Lire::Program qw( :msg );

lr_err( "Usage: lr_inflate [logfile]" ) if @ARGV > 1;

my $fh;
if ( @ARGV ) {
    open( FILE, $ARGV[0] )
      or lr_err( "can't open $ARGV[0]: $!\n" );
    $fh = \*FILE;
} else {
    $fh = \*STDIN;
}

# Read magic
my $magic;
read $fh, $magic, 4;
lr_err( "read failed: $!\n" ) unless defined $magic;

# Check for empty file
exit 0 if !length $magic;

# Check for compressed content
my $compress;
if ( substr($magic,0,2) eq "\037\235" ) {
    $compress = "compress";
} elsif ( substr($magic,0,2) eq "\037\213" ) {
    $compress = "gzip"
} elsif ($magic eq "PK\003\004" ) {
    $compress = "zip"
} 

my $out_fh = \*STDOUT;
if ( $compress ) {
    lr_info( "content was compressed using $compress" );
    lr_err( "can't uncompress: gzip(1) wasn't found by configure" )
      unless defined $Lire::Config::gzip && $Lire::Config::gzip ne 'no';
    lr_err( "can't uncompress: $Lire::Config::gzip isn't executable" )
      unless -x $Lire::Config::gzip;

    # Clean the environment
    local %ENV = ();
    open( GZIP, "|$Lire::Config::gzip -dc" )
      or lr_err( "failed to fork: $!\n" );
    $out_fh = \*GZIP;
} 

# Copy the content to gzip or stdout
print $out_fh $magic;
my $buffer;
while ( read $fh, $buffer, 1024**2 ) {
    print $out_fh $buffer;
}
lr_err( "read failed: $!\n") unless defined $buffer;

if ( $compress ) {
    close GZIP
      or lr_err( "gzip exited with non zero status: $?" );
}

# Local Variables:
# mode: cperl
# End:

__END__

=pod

=head1 NAME

lr_inflate - filter that will uncompress compressed log files 

=head1 SYNOPSIS 

B<lr_inflate> [<logfile>]

=head1 DESCRIPTION

B<lr_inflate> will read a file on STDIN or given as argument and
output it on STDOUT. If the file is compressed (as determine by the
magic bytes), it will be uncompressed.

This script is called by lr_log2report(1)

=head1 VERSION

$Id: lr_inflate.in,v 1.2 2002/04/07 19:27:22 flacoste Exp $

=head1 COPYRIGHT

Copyright (C) 2002 Stichting LogReport Foundation LogReport@LogReport.org
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html or write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.

=head1 AUTHOR

Francis J. Lacoste <flacoste@logreport.org>

=cut


