#!/usr/bin/perl

use v5.10;
use strict;
use warnings;

use File::Basename;
use Linux::Inotify2;

#my $to = 600;
my $to = 60;

my $inotify = new Linux::Inotify2
  or die "unable to create new inotify object: $!";
$inotify->blocking(0);

my %size;
my $deadline;

my $ME = basename $0;

sub delay_exit {
    my $fn = shift;
    $deadline = time + $to if $size{ basename $fn};
}

sub verify_size {
    my $fn = shift;
    delay_exit $fn;
    my $bn = basename $fn;
    my $s  = -s $fn;
    delete $size{$bn} if defined $s and $s >= $size{$bn};
}

my $incoming = "$ENV{HOME}/incoming";
my $nfiles   = 0;
my $c        = "$incoming/$ARGV[0]";

my @cmd = ("$ENV{HOME}/bin/rpi", $c);

open C, '<', $c or die "Can't open '<$c': $!\n";
my $skip = 1;
while (<C>) {
    no warnings qw(syntax);
    if (/^files:\s*$/i) { $skip = 0; next; }
    use warnings;
    next if $skip;
    last unless (/^ ([^ ]+) +([^ ]+) +([^ ]+) +([^ ]+) +([^ \n]+) *$/);
    $size{$5} = $2;
    $nfiles++;
}
close C;
warn "$ME: no files found in changes file.\n" unless $nfiles;

$inotify->watch($incoming, IN_MODIFY,
    sub { my $e = shift; delay_exit $e->fullname; })
  or warn "Can't watch: $!";
$inotify->watch($incoming, IN_CLOSE,
    sub { my $e = shift; verify_size $e->fullname; })
  or warn "Can't watch: $!";

# do initial check on file in case its upload is already finished
verify_size "$incoming/$_" for keys %size;

my $done = 0;
do {

    $inotify->poll;
    if (time > $deadline) {
        warn "$ME: file upload timed out.\n";
        $done = 1;
    }

    $done = 1 unless %size;

    if ($done) {
        exec @cmd if @cmd;
        exit;
    }

} while (sleep 1);

__END__

=head1 NAME

waitfordeb - watch incoming directory for debian package upload completion

=head1 SYNOPSIS

waitfordeb changesfile

waitfordeb -m|--man
           -h|--help

=head1 DESCRIPTION

In an ideal world every package maintainer would use a tool which reliably
uploads the changes file as the last file. But sometimes this does not happen
and reprepro may fail the import. 

=head1 AUTHORS

Matthias Förste L<<foerste@schlittermann.de>>

=cut
