#! /usr/bin/perl
# © 2006 Heiko Schlittermann

use strict;
use warnings;
use File::Find;
use Cwd;
use FindBin;
use File::Basename;
use File::Path;
use AppConfig;

use lib "$FindBin::RealBin/../lib";
use Debian::ChangesFile;

use constant CONF => (
    { CASE => 1 },
    "force" =>	{ ARGS => "!" },
);

sub processChanges;

my $TIMESTAMP = "var/.import";
my $POOLDIR = "pool";
my $Cf = new AppConfig CONF or die;
   $Cf->getopt or die;

MAIN: {
    my $cwd = cwd();

    $POOLDIR = "$cwd/$POOLDIR" if substr($POOLDIR, 0, 1) ne "/";
    $TIMESTAMP = "$cwd/$TIMESTAMP" if substr($TIMESTAMP, 0, 1) ne "/";

    $Cf->force and unlink $TIMESTAMP;


    my $last = (stat $TIMESTAMP)[9] || 0;
    my $changed = 0;
    my $wanted = sub { processChanges($last, \$changed) };

	# Two! slashes
	find({ wanted => $wanted}, "incoming//");

    if ($changed) {
	open(X, ">$TIMESTAMP");
	print X $$;
	close(X);
    }

}

sub processChanges($$) {
    my $last = shift;
    my $touched = shift;

    -f or return;
    /\.changes$/ or return;
    (stat $_)[9] >= $last or return;

    my $current = $_;
    my ($base) = $File::Find::dir =~ m!//(.*)!;

    print "checking $File::Find::name\n" if -t STDIN;
    my @import;

    my $changes = new Debian::ChangesFile($_);

    push @import, [$_, "$POOLDIR/$base/" . $_];

    foreach ($changes->binaryFiles) {
	print "\t", $_->file, "\n" if -t STDIN;
	$_->check;
	push @import, [$_->file, "$POOLDIR/$base/" . $_->file];
    }

    foreach ($changes->sourceFiles) {
	print "\t", $_->file, "\n" if -t STDIN;
	$_->check;
	push @import, [$_->file, "$POOLDIR/$base/" . $_->file];
	my $sources = new Debian::ControlFile $_;
	foreach ($sources->files) {
	    print "\t\t", $_->file, "\n" if -t STDIN;
	    $_->check();
	push @import, [$_->file, "$POOLDIR/$base/" . $_->file];
	}
    }

    print "ok ($current)\n" if -t STDIN;

    foreach (@import) {
	my ($from, $to) = @$_;
	my $dstdir = dirname($to);
	-d $dstdir or mkpath($dstdir, 0, 0755) or die "Can't mkpath $dstdir: $!\n";
	my $in = new IO::File $from or die "Can't open <$from: $!\n";
	my $out = new IO::File ">$to.tmp" or die "Can't open >$to.tmp: $!\n";

	local $/ = \4096;
	$out->print($_) while <$in>;
	$out->close;
	$in->close;

	utime((stat $from)[8, 9], "$to.tmp") or die "Can't change timestamps on $to: $!\n";
	rename("$to.tmp", $to) or die "Can't rename $to.tmp -> $to: $!\n";
	$$touched = 1;
    }

}

# vim:sts=4 sw=4 aw ai sm:
