#!/usr/bin/perl
# Generates from the package-list a dependency file, suitable to be fed to
# tsort. The file has the base package name on the left, and the package it
# depends on is on the right. It is sorted.

my $arch=`dpkg-architecture -qDEB_HOST_ARCH`;
chomp $arch;

my $flavour=$ARGV[0];

my @out;

sub read_package_list
{
	my $file = shift;
	open(LIST, $file) || die "package-list: $!";
	my $package;
	while (<LIST>) {
		chomp;
		next if /^#/;

		if (/^Package:\s*(.*)/) {
			$package=$1;
		}
		elsif (/Depends:\s*(.*)/) {
			my @depends=split(", ", $1);
			# Skip packages that are not built for this architecture.
			my $modlistdir="";
			if (-d "modules/$arch-$flavour") {
				$modlistdir="modules/$arch-$flavour";
			}
			elsif (-d "modules/$flavour") {
				$modlistdir="modules/$flavour";
			}
			else {
				$modlistdir="modules/$arch";
			}

			my $fwlistdir="";
			if (-d "firmware/$arch-$flavour") {
				$fwlistdir="firmware/$arch-$flavour";
			} elsif (-d "firmware/$flavour") {
				$fwlistdir="firmware/$flavour";
			} else {
				$fwlistdir="firmware/$arch";
			}

			next unless -e "$modlistdir/$package" or -e "$fwlistdir/$package";

			foreach my $dep (@depends) {
				# Skip depends that are not built for this
				# architecture.
				next unless -e "$modlistdir/$dep" or -e "$fwlistdir/$dep";
				push @out, "$package\t$dep\n";
			}
		}
	}
	close LIST;
}

read_package_list("/usr/share/kernel-wedge/package-list");
read_package_list("package-list");
print sort @out;
