#!/usr/bin/perl -w
#
# Copyright (c) 2005 -  2007 Miek Gieben; Mark J Hewitt
# See LICENSE for the license
#
use strict;

use Getopt::Std;
use File::Basename;
use File::Temp qw{tempdir tempfile};
use File::Spec;
use POSIX;

# common functions
my $prefix="/usr";
my $datarootdir = "${prefix}/share";
require "${datarootdir}/rdup/shared.pl"; 

my $progName = basename $0;
my %opt;
my $zipOptions = "-f ";

getopts('dhV', \%opt);
usage() if $opt{'h'};
version($progName) if $opt{'V'};
$zipOptions .= "-d " if $opt{'d'};

my $tmpDir = tempdir("rdup.backup.XXXXXX", TMPDIR => 1, CLEANUP => 1);
die "** $tmpDir could not be created: $!" unless -d $tmpDir;

`which gzip >/dev/null`;
if ($? != 0) {
	die "** Cannot find \'gzip'";
}

while (<STDIN>) {
        chomp;
        my ($t, $bits, $uid, $gid, $psize, $fsize) = split(" ", $_, 6);
        my $dump = substr($t, 0, 1);
        my $type = substr($t, 1, 1);

        sanity_check($dump, $bits, $psize, $fsize, $uid, $gid);

        my $path = "";
        read STDIN, $path, $psize;
        die "** Empty path"  if ($path eq "");

        if ($dump eq '+') {        # add
                if ($type eq '-') {      # REG
                        if ($fsize != 0) {
                                my($fh, $filename) = tempfile("file.XXXXX", DIR => $tmpDir, SUFFIX => ".gz" );
                                $fh->close();
                                open ZIP, "|gzip $zipOptions -c > $filename" or die "** $filename: $!";
                                copyout($fsize, *ZIP);
                                close ZIP or warn "** Zip failure: \'$path': $!";
                                my $size = (stat($filename))[7];
                                syswrite STDOUT, "$dump$type $bits $uid $gid $psize $size\n$path";
                                catfile($filename);
                                unlink $filename;
                                next;
                        }
                        syswrite STDOUT, "$dump$type $bits $uid $gid $psize $fsize\n$path";
                        next;
                } 
	}
	syswrite STDOUT, "$dump$type $bits $uid $gid $psize $fsize\n$path";
}

sub usage {
        print "$progName [OPTIONS]\n\n";
        print "Compress or decompress the file's contents\n\n";
        print "OPTIONS:\n";
        print " -c    ignored as rdup-gzip always works on content\n";
        print " -d    decompress the files\n";
        print " -h    this help\n";
        print " -V    print version\n";
        exit;
}
