#!/usr/bin/perl

use warnings;
use strict;

my $psuite = $ARGV[0];
$psuite or die "Usage: gen-build-deps <previous suite name>";
$ENV{DEBATHENA_APT} or $ENV{DEBATHENA_APT}="/mit/debathena/apt";

sub list {
	my ($l) = @_;
	my @a = split(/, /, $l);
	foreach (@a) {
	    s/ \(.*\)$//;
	    s/ \|.*$//;
	    s/ \[.*$//;
	}
	return @a;
}

# For each source package, add its build-deps to the list
open(DPKG, '-|', "zcat $ENV{DEBATHENA_APT}/dists/$psuite/*/source/Sources.gz | dpkg-awk -f - -- Package Build-Depends") or die;
my %src_deps = ();
while (<DPKG>) {
	last if /^$/;
	my ($source) = /^Package: (.*)$/ or die;
	@{$src_deps{$source}} = ();
	while (<DPKG>) {
		last if ($_ eq "\n");
		if (my ($depends) = /^Build-Depends: (.*)$/) {
			push @{$src_deps{$source}}, $_ for (list($depends));
		} else {
			die;
		}
	}
}
close DPKG;

# For each binary package, add itself as a source and provider.  If
# there are actually different Sources and Provides for the package,
# use them instead.  Note: This will fail miserably if we ever build
# packages only for one architecture.
open(DPKG, '-|', "zcat $ENV{DEBATHENA_APT}/dists/$psuite/debathena/binary-amd64/Packages.gz | dpkg-awk -f - -- Package Source Provides Depends") or die;
my %pkg_src = ();
my %pkg_provider = ();
my %pkg_deps=();
while (<DPKG>) {
	last if /^$/;
	my ($package) = /^Package: (.*)$/ or die;
	$pkg_src{$package} = $package;
	$pkg_provider{$package} = $package;
	@{$pkg_deps{$package}} = ();
	while (<DPKG>) {
		last if ($_ eq "\n");
		if (my ($source) = /^Source: (.*)$/) {
			$pkg_src{$package} = $source;
		} elsif (my ($provides) = /^Provides: (.*)$/) {
			$pkg_provider{$_} = $package for (list($provides));
		} elsif (my ($depends) = /^Depends: (.*)$/) {
			push @{$pkg_deps{$package}}, $_ for (list($depends));
		} else {
			die;
		}
	}
}

for my $source (keys %src_deps) {
	print "build-all: \$(call package,$source)\n";
	if ($source ne "debathena-build-depends") {
	    print "\$(call package,debathena-build-depends): \$(call package,$source)\n";
	}
	for (@{$src_deps{$source}}) {
		print "\$(call package,$source): \$(call package,$pkg_src{$pkg_provider{$_}})\n" if (defined $pkg_provider{$_});
		foreach my $dep (@{$pkg_deps{$_}}) {
		    print "\$(call package,$source): \$(call package,$pkg_src{$dep})\n" if (defined $pkg_provider{$dep});
		}
	}
}
