#!/usr/bin/perl -w
use strict;
use File::Find;
use Getopt::Std;
use Digest;

our $opt_d=0;
our $opt_m=0;
our $opt_n;
getopts("dmn"); # d: delete files that fail to match digest
                # m: list files that are missing
                # n: don't actually look at md5 hash
my $filecount=0;
my %files;
sub readPack {
    my $sc=$_;
    my ($f,$s,$m);
	
    return unless $_ eq "Packages";
    open P,"<$sc" or die "can't read package file $File::Find::name";
    while (<P>) {
	if (/^Filename: (.*)$/) {
	    $f = $1;
	}
	if (/^Size: (.*)$/) {
	    $s = $1;
	}
	if (/^MD5sum: (.*)$/) {
	    $m = $1;
	    if ($files{$f}) {
		if ($files{$f}->[0] != $s or
		    $files{$f}->[1] ne $m) {
		    print "pre-existing file entry error!\n";
		    print "There are two entries for $f in Packages files\n";
		    print "that don't agree.\n";
		}
	    } else {
		$filecount++;
	    }
	    $files{$f} = [ $s, $m ];
	}
    }
    close P;
    $_ = $sc;
}
print "Read Package files\n";
find \&readPack, "debian/dists";
print "done.  Found $filecount files referenced in Package files\n";

sub got_int {
	print "bye...\n";
	exit 1;
}
$SIG{'INT'} = \&got_int;

my $digest;
my $sizeprob;
my $digestprob;
my $digester = Digest->new('MD5');
foreach my $f ( sort keys %files ) {
    if (-r "debian/$f") {
	$sizeprob = ((stat(_))[7] != $files{$f}->[0]);
	if ($opt_n) {
	    $digestprob = 0;
	} else {
	    if (open F,"debian/$f") {
		$digester->addfile(*F);
		close F;
		$digest = $digester->hexdigest;
		$digestprob = ((split(' ',$digest))[0] ne $files{$f}->[1]);
	    } else {
		print "can't open debian/$f to look at md5 sum\n";
		$digestprob=1;
	    }
	}
	if ($sizeprob or $digestprob) {
	    print "check $f: [",join(',',@{$files{$f}}),"]\n";
	    if ($sizeprob) {
		print "  size mismatch, ", (stat(_))[7], "\n";
	    }
	    if ($digestprob) {
		print "  digest mismatch, ", (split(' ',$digest))[0], "\n";
	    }
	    if ($opt_d) {
		print "delete debian/$f\n";
		unlink "debian/$f";
	    }
	}
    } elsif ($opt_m) {
	print "debian/$f is missing\n";
    }
}

print "done.\n";
