#!/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;

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

if (!defined($ARGV[0]) or ! -f $ARGV[0]) {
        die "** Cannot open keyfile";
}
`which mcrypt >/dev/null`;
if ($? != 0) {
	die "** Cannot find \'mcrypt'";
}

$crOptions .= "-q -F -f $ARGV[0] -a blowfish";

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

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 => ".nc" );
                                $fh->close();
                                open CRYPT, "|mcrypt $crOptions 2>/dev/null > $filename" or die "** $filename: $!";
                                copyout($fsize, *CRYPT);
                                close CRYPT or warn "** Crypt failure: result will be empty \`$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] KEYFILE\n\n";
        print "Encrypt or decrypt the file's contents with the\n";
        print "key stored in KEYFILE\n\n";
        print "OPTIONS:\n";
        print " -c    ignored as rdup-crypt always works on content\n";
        print " -d    decrypt the files\n";
        print " -h    this help\n";
        print " -V    print version\n";
        exit;
}
