#!/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 $exit_after;

my $ME = basename $0;

sub delay_exit {
    my $fn = shift;
    $exit_after = 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]";

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 > $exit_after) {
        warn "$ME: file upload timed out.\n";
        $done = 1;
    }

    $done = 1 unless %size;
    exec "$ENV{HOME}/bin/rpi" if $done;

} while (sleep 1);
