#!/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";

my $debugmode = $ENV{DEBATHENA_DEBUG} ? 1 : 0;

sub debug {
    if ($debugmode) {
	print STDERR "D: ", @_, "\n";
    }
}

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;
	debug("Examining $source");
	@{$src_deps{$source}} = ();
	while (<DPKG>) {
		last if ($_ eq "\n");
		if (my ($depends) = /^Build-Depends: (.*)$/) {
		    for (list($depends)) {
			debug("  Adding $_ as build-dep of $source");
			push @{$src_deps{$source}}, $_ ;
		    }
		} 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;
	debug("Examining binary package $package");
	$pkg_src{$package} = $package;
	$pkg_provider{$package} = $package;
	debug("Setting src and provider to itself");
	@{$pkg_deps{$package}} = ();
	while (<DPKG>) {
		last if ($_ eq "\n");
		if (my ($source) = /^Source: (.*)$/) {
			$pkg_src{$package} = $source;
			debug("  Changing src to $source");
		} elsif (my ($provides) = /^Provides: (.*)$/) {
		    for (list($provides)) {
			$pkg_provider{$_} = $package;
			debug("  Adding $package as a provider of $_");
		    }
		} elsif (my ($depends) = /^Depends: (.*)$/) {
			for (list($depends)) {
			    push @{$pkg_deps{$package}}, $_;
			    debug("--Adding $_ to dependencies of $package");
			}
		} 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});
		}
	}
}
