#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

# Copyright (c) 2002 Philip Hands <phil@hands.com>
# See the README file for the license

# This script creates the md5sums files, using the precalculated md5sums
# from the main archive
# First arg = the build directory

use strict;
use Digest::MD5;

# load up all the md5sums we need
my %md5 ;
my $BDIR = shift @ARGV ;

foreach my $sumsfile ($BDIR . "/indices/md5sums", $BDIR . "/indices-non-US/md5sums") {
  if (open(MD5SUMS, $sumsfile)) {
    while (<MD5SUMS>) {
      chomp;
      next if /Packages/ ;
      next if /Sources/ ;
      next if /Release/ ;
      my ( $sum, $name ) = split(' ') ;
      # printf "[%s] [%s]\n", $sum, $name ;
      $md5{$name} = $sum ;
    }
    close(MD5SUMS);
  } else {
    warn "Couldn't open file: $sumsfile";
  }
}

#foreach my $f (keys(%md5)) {
#  printf "[%s] [%s]\n", $f, $md5{$f} ;
#}

foreach my $dir (<$BDIR/CD*>) {
  chdir $dir ;
  open(FILES, "find . -follow \\(   -path '*dists/stable*'              \\
                                 -o -path '*dists/frozen*'              \\
                                 -o -path '*dists/unstable*' \\) -prune \\
                              -o -type f ! -path '\./md5sum*' -print|"    ) || die ;
  open(MD5OUT, ">md5sum.txt") || die "Couldn't open file for writing: md5sum.txt, in $dir" ;
  while(<FILES>) {
    chomp;
    s(^\./)() ;
    if (!defined($md5{$_})) {
       open(FILE, $_) or die "Can't open '$_': $!";
       binmode(FILE);
       # printf STDERR "md5-ing %s", $_ ;
       #$md5{$_} = Digest::MD5->new->addfile(*FILE)->hexdigest ;
       printf MD5OUT "%s  ./%s\n",
	 Digest::MD5->new->addfile(*FILE)->hexdigest, $_;
# FIXME:
# the ./ in the printf above is only there to keep byte-for-byte compatibility
# with the find . output used before -- It should probably be removed
#
       # printf STDERR ".\n" ;
       close(FILE) ;
    } else {
       printf MD5OUT "%s  ./%s\n", $md5{$_}, $_;
    }
  }
  close(MD5OUT);
  die "$dir/md5sum.txt is empty!\n" unless (-s "md5sum.txt");
}
