#!/usr/bin/perl -w
# Generate a list of packages required for debian-installer
# This script makes use of the following variables that need to be preset:
# MIRROR, DI_CODENAME, BASEDIR
die "Missing \$MIRROR variable" unless $ENV{MIRROR};
die "Missing \$DI_CODENAME variable" unless $ENV{DI_CODENAME};
die "Missing \$BASEDIR variable" unless $ENV{BASEDIR};

my @ARCHES=qw{alpha arm hppa hurd-i386 i386 ia64 m68k mips mipsel
              powerpc s390 sparc amd64};
my $DATE=`date`;
chomp $DATE;
open(OUT, ">debian-installer-$ENV{DI_CODENAME}") || die "write: $!";
print OUT << "EOF";
/* List of udebs to be included so that debian-installer works fine 
 *
 * This list can be generated with the command:
 * ../tools/generate_di_list
 *
 * DO NOT EDIT THIS FILE, edit the above script
 *
 * Last update: $DATE
 */
EOF

my @common_excludes = read_exclude("exclude-udebs");

foreach my $arch (@ARCHES) {
	my $packagefile="$ENV{MIRROR}/dists/$ENV{DI_CODENAME}/main/debian-installer/binary-$arch/Packages.gz";
	unless (-f $packagefile) {
		print "Missing package file for arch $arch.\n";
		next;
	}
	(my $cpparch = $arch) =~ s/-/_/g;
	print OUT "#ifdef ARCH_$cpparch\n";
	my @exclude = @common_excludes;
	push @exclude, read_exclude("exclude-udebs-$arch")
		if -e exclude_path("exclude-udebs-$arch");
UDEB:	foreach my $udeb (map { chomp; $_ } `zcat $packagefile | awk '/^Package:/ {print \$2}'`) {
		foreach my $pattern (@exclude) {
			if ($udeb =~ /^$pattern$/) {
				next UDEB;
			}
		}
		print OUT "$udeb\n";
	}
	print OUT "#endif /* ARCH_$cpparch */\n";
}

sub read_exclude {
	my $file=exclude_path(shift);
	open (IN, "<$file") || warn "failed to read exclude file $file";
	my @ret;
	while (<IN>) {
		chomp;
		s/^#.*//;
		next unless length;
		$_=quotemeta($_);
		$_=~s/\\\*/.*/g;
		push @ret, $_;
	}
	close IN;
	return @ret;
}

sub exclude_path {
	my $file=shift;
	return "$ENV{BASEDIR}/data/$ENV{DI_CODENAME}/$file";
}