#! /usr/bin/perl -w
use strict;

use Dpkg::Deps;

# Get the first in a list of or-ed dependencies.
sub first_dep ($) {
	my $inner = shift;
	while ($inner->isa('Dpkg::Deps::OR')) {
		my @deps = $inner->get_deps();
		$inner = $deps[0];
	}
	unless ($inner->isa('Dpkg::Deps::Simple')) {
		die sprintf "Couldn't reduce $inner to a simple dependency!\n";
	}
	return $inner;
}

my $control = 'debian/control';
unless (-e $control) {
	$control = '../debian/control';
	unless (-e $control) {
		die "cannot find debian/control";
	}
}

my %builddeps;

# Always include base ubiquity build dependencies.
my @basebd = (
    'apt',
    'dctrl-tools',
    'debconf-utils',
    'debhelper (>= 7.0.1)',
    'dh-di (>= 3)',
    'dpkg-dev (>= 1.14.4)',
    'gir1.2-soup-2.4',
    'gir1.2-timezonemap-1.0',
    'gnome-icon-theme',
    'intltool (>= 0.40.0)',
    'libcairo2-dev',
    'keymapper (>= 0.5.3-7)',
    'libgirepository1.0-dev',
    'libglib2.0-dev',
    'libgstreamer-plugins-base0.10-dev (>= 0.10.23)',
    'libgtk-3-dev',
    'libgudev-1.0-dev',
    'libindicator3-dev',
    'liblocale-gettext-perl',
    'gobject-introspection',
    'pkg-config',
    'po-debconf (>= 1.0)',
    'pyflakes',
    'python-all (>= 2.6.6-3~)',
    'python-apt (>= 0.7.100.3~)',
    'python-cairo',
    'python-dbus',
    'python-gi-cairo',
    'python-gi-dev',
    'python-libxml2',
    'python-mock (>= 0.7.0)',
    'python-pyicu (>= 1.0)',
    'python-scour',
    'gir1.2-xkl-1.0',
    'ubuntu-artwork',
    'udev',
    'xkb-data (>= 0.9)',
    'xkb-data-i18n',
    'xvfb',
);
my $basebd = join ', ', @basebd;
my $parsed = Dpkg::Deps::deps_parse($basebd, reduce_arch => 1);
for my $bd ($parsed->get_deps()) {
	my $firstbd = first_dep($bd);
	$builddeps{$firstbd->{package}} = $firstbd;
}

for my $source (<source/*/debian/control>) {
	# We don't build console-setup, so skip its build-dependencies.
	next if $source eq 'source/console-setup/debian/control';
	open SOURCE, '<', $source or die "can't open $source: $!";
	while (<SOURCE>) {
		if (/^Build-Depends(?:-Indep)?:\s*(.*)/i) {
			$parsed = Dpkg::Deps::deps_parse($1, reduce_arch => 1);
			for my $bd ($parsed->get_deps()) {
				# Reduce any or-ed dependencies to the first
				# alternative.
				my $firstbd = first_dep($bd);
				my $package = $firstbd->{package};
				if (not exists $builddeps{$package} or
				    $firstbd->implies($builddeps{$package})) {
					$builddeps{$package} = $firstbd;
				}
			}
			next;
		}
	}
	close SOURCE;
}

my $builddeps =
	join ', ', map { "$builddeps{$_}" } sort keys %builddeps;
open IN, '<', $control or die "can't open $control: $!";
open OUT, '>', "$control.tmp" or die "can't open $control.tmp for writing: $!";
foreach (<IN>) {
	s/^(Build-Depends:\s*)(.*)/$1$builddeps/;
	print OUT or die "can't print to $control.tmp: $!";
}
close OUT or die "can't close $control.tmp: $!";
close IN;
rename "$control.tmp", $control
	or die "can't rename $control.tmp to $control: $!";
