#!/usr/bin/perl -w

use Getopt::Std;

$0 =~ s:(.*)/:: or die "$0: unknown path\n";
$fexdox = $1.'/fexdox';
$| = 1;

$usage = "$0: fexdox new created or modified files
usage: $0 [-v] [-n] [-w SECONDS] [-m MAX] [-d] DIRECTORY
options:
  -v  verbose mode
  -n  dry-run without transfer
  -w  wait SECONDS to check for new files (default: 60)
  -m  limit throuput to MAX kB/s
  -d  delete extraneous files
";

$ENV{FUA} = 'autodox';

$opt_h = $opt_v = $opt_n = $opt_d = 0;
$opt_w = 60;
$opt_i = $opt_m = '';
getopts('hvndw:i:m:') or die $usage;

$wait = 10;
$wait = $1 if $opt_w =~ /^(\d+)$/;

if ($opt_h) {
  print $usage;
  exit;
}

if (scalar(@ARGV) != 1) {
  die $usage;
}

$dir = shift;
chdir $dir or die "$0: $dir - $!\n";

@fexdox = ($fexdox,'-s');
push @fexdox,'-d' if $opt_d;
push @fexdox,('-m',$opt_m) if $opt_m;
push @fexdox,('-i',$opt_i) if $opt_i;

$comment = 'waiting for new files... ';
%files = ();
$t0 = time;
collect('.');
vsystem(@fexdox,'.');

for (;;) {
  if (-t STDOUT) {
    for (my $i = $wait; $i; $i--) {
      printf "%s%3d\r",$comment,$i;
      sleep 1;
    }
    print ' ' x length($comment),"   \r";
  } else {
    sleep $wait;
  }

  %ofiles = %files;
  @files = ();
  $t0 = time;
  collect('.');

  foreach my $file (keys %files) {
    if ($files{$file} != ($ofiles{$file}||0)) {
      vsystem(@fexdox,'.');
      last;
    }
  }

}



# collect all files
sub collect {
  my $DIR;
  my ($dir,$file);
  local $_;

  foreach $dir (@_) {
    if (-l $dir or -f $dir) {
      $file = $dir;
      if (-l $file or -r $file) {
        if (my @s = lstat $file) {
          $files{$file} = $s[9];
        }
      } else {
        warn "$prg: cannot read $::dir/$file - $!\n";
        $error++;
      }
    } elsif (opendir $DIR,$dir) {
      my @files = ();
      while (defined(my $file = readdir $DIR)) {
        next if $file =~ /^\.\.?$/;
        $file = "$dir/$file" if $dir ne '.';
        if ($file =~ s/\n/?/g) {
          warn "$prg: ignoring file with newline character in filename: $file\n";
          next;
        }
        push @files,$file;
      }
      closedir $DIR;
      collect(@files);
    } else {
      warn "$prg: cannot open $::dir/$dir/ - $!\n";
      $error++;
    }
  }
}


sub isodate {
  my @d = localtime shift;
  return sprintf('%d-%02d-%02d %02d:%02d:%02d',
                 $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]);
}


sub vsystem {
  print "\$ @_\n" if $opt_v;
  system @_ unless $opt_n;
  print "\n";
}
