#!/usr/bin/perl

# This is a hacky perl script to get around the lack of apt-ma-emu and a
# sensible cross-dependency install script in a pbuilder-compatible manner.
# hooks have to work out where things are inside the chroot, which can be a problem.

#  Copyright 2010 Neil Williams <codehelp@debian.org>
#
#  This package is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use warnings;
use File::Basename;
use Term::ANSIColor qw(:constants);
use vars qw/ @aptlist @bits $use_sudo $name $dryrun $tools $deps
 @dependencies $cmd /;

system ("apt-get -y install apt-cross libparse-debianchangelog-perl realpath");
system ("apt-cross -v -u 2>/dev/null");

my $ctrl = `find /tmp/buildd/ -path "*/debian/control"|head -n1`;
chomp ($ctrl);
my $dir = dirname ($ctrl);
chomp ($dir);
$dir = `realpath $dir/../`;
chomp ($dir);
print "Changing to '$dir/'\n";
chdir ("$dir/");
$name=`dpkg-parsechangelog|grep Source:`;
chomp ($name);
$name =~ s/Source: //;
my @xc=();
if (-f "debian/xcontrol")
{
	open (XC, "<debian/xcontrol");
	@xc=<XC>;
	close (XC);
}
# allow multi-lines
my $str = join ("", @xc);
$str =~ s/\n / /g;
$str =~ s/  / /g;
my @long = split ("\n", $str);
@dependencies=();
foreach my $line (@long)
{
	if ($line =~ /^Build-Depends-Tools: /)
	{
		$line =~ s/^Build-Depends-Tools: //;
		$tools = $line;
	}
	if ($line =~ /^Build-Depends: /)
	{
		$line =~ s/^Build-Depends: //;
		$deps = $line;
		$deps =~ s/ +/ /g;
	}
}
@dependencies=split(/, /, $deps) if (defined $deps);
@aptlist=();
foreach my $dep (@dependencies)
{
	$dep =~ s/^ //;
	@bits=split(/ /, $dep);
	push @aptlist, $bits[0];
}
print ("Checking that build dependencies for $name are installed:\n");
if (scalar @aptlist > 0) {
	$cmd = "apt-cross -q -q -i ".join(" ", @aptlist);
	print "Running '$cmd'\n";
	print "       This takes a long time and might produce little or no output until the end - please wait!\n";
	system ("$cmd");
}
system ("rm -f *.deb");
chdir ("/");
