#!/usr/bin/perl

use strict;

use lib "$ENV{APB_HOME}/lib";
use AutoPkgBuilder;
use FileHandle;
use IPC::Open3;

use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

sub dpkg_checkbuilddeps {
    my $dir = shift;
    my ($w, $r, $e);
    open3($w, $r, $e, "/usr/bin/dpkg-checkbuilddeps", "$dir/debian/control");
    my $line = join("", <$r>);
    $line =~ s/^[^:]+: //;
    close($w);
    close($r);
    wait;
    return ($?, $line);
}

sub main {
    my $ifile = "$APB_HOME/var/SRCDIRS";
    my $nfile = "$APB_HOME/var/BUILD_NODEPS";
    my $dfile = "$APB_HOME/var/BUILD_DEPS";
    my $hfile = "$APB_HOME/var/BUILD_IOHACK";
    my $lfile = "$APB_HOME/log/check-build-deps.log";
    my $ifh = new FileHandle($ifile) or die "Can't open $ifile ($!)";
    my $nfh = new FileHandle($nfile, "w") or die "Can't open $nfile ($!)";
    my $dfh = new FileHandle($dfile, "w") or die "Can't open $dfile ($!)";
    my $hfh = new FileHandle($hfile, "w") or die "Can't open $hfile ($!)";
    my $lfh = new FileHandle($lfile, "w") or die "Can't open $lfile ($!)";
    chdir("$APB_HOME/build");
    local $_;
    while (<$ifh>) {
	chomp;
	my ($pkg, $ver, $iohack, $dir) = split;
	my ($status, $msg) = dpkg_checkbuilddeps($dir);
	$lfh->print("[$pkg]\n$msg");
	msg("[$pkg]\n$msg");
	if ($iohack || -f "$APB_HOME/iohack/$pkg.sh") {
	    $hfh->print("$pkg\t$ver\t$dir\n");
	    $lfh->print("type = iohack\n");
	    msg("type = iohack\n");
	} elsif ($status) {
	    $dfh->print("$pkg\t$ver\t$dir\n");
	    $lfh->print("type = deps\n");
	    msg("type = deps\n");
	} else {
	    $nfh->print("$pkg\t$ver\t$dir\n");
	    $lfh->print("type = nodeps\n");
	    msg("type = nodeps\n");
	}
    }
    $lfh->close;
    $hfh->close;
    $dfh->close;
    $nfh->close;
    $ifh->close;
}

main;
