#!/usr/pkg/bin/perl
use strict;

if (@ARGV and $ARGV[0] eq "--help") {
    print
q(This script will test magicrescue on existing files on your hard disk to see
if your recipe is good enough. It can be very useful when creating or modifying
a recipe.

Usage:
./magicrescue -Mio OPTIONS FILES|tools/checkrecipe [OPTIONS]

Options:
  -s VALUE  Size tolerance, in percent. Specifies when checkrecipe should
            complain about the output file size being different from the input.

Usage examples:

find / -name \*.png -print0 \
|xargs -0 ./magicrescue -Mio -r png -d /tmp/test-output 2>/dev/null \
|tools/checkrecipe

  or

slocate \*.png|sed "s/['\"\\\\[:blank:]]/\\\\\\\\&/g" \
|xargs ./magicrescue -Mio -r png -d /tmp/test-output 2>/dev/null \
|tools/checkrecipe
);
    exit;
}

my $size_tolerance = 0;

while (defined(my $arg = shift(@ARGV))) {
    if ($arg eq "-s") {
	$size_tolerance = shift(@ARGV)/100;
    } else {
	die "$0: Unknown option $arg. Use --help for usage info.\n";
    }
}

my ($curfile, $cur_ok);
while (<STDIN>) {
    if (/^i (.*)$/) {
	if ($curfile and !$cur_ok and -s $curfile) {
	    print "$curfile: not extracted\n";
	}
	$curfile = $1;
	$cur_ok = 0;
    } elsif (/^o (.*)$/) {
	my $outfile = $1;
	if ($curfile and $cur_ok) {
	    print "$curfile: extracted again\n";

	} else {
	    my ($insize, $outsize) = (-s $curfile, -s $outfile);
	    if ($size_tolerance >= 0 and $insize and -f $outfile 
		    and abs($outsize - $insize)/$insize > $size_tolerance) {
		print "$curfile: is $insize bytes, extracted $outsize bytes\n";
	    }
	}

	$cur_ok = 1;
	unlink $outfile or warn "unlinking $outfile: $!";
    }
}

