#!/usr/bin/perl -- -*- mode: cperl -*-

=head1 NAME

rrr-dirtyupdate - add a file with an old timestamp to the dataset

=head1 SYNOPSIS

  rrr-dirtyupdate [options] principalfile file [epoch]

  rrr-dirtyupdate --force principalfile

=head1 OPTIONS

=over 8

=cut

my @opt = <<'=back' =~ /B<--(\S+)>/g;

=item B<--delete>

Inject a delete event. If the epoch argument is missing, find the
according file event and set epoch to that epoch plus 1.

=item B<--force|f>

Force this run even without any arguments. E.g. just for the side
effect of running an aggregate call.

=item B<--help|h>

Prints a brief message and exists.

=item B<--verbose|v+>

More feedback.

=back

=head1 DESCRIPTION

When you later discover missing files...

The principalfile argument is the path to local principal recentfile.

The file argument is a relative path calculated from the localroot
directory of the recentfile object.

If the epoch argument is missing it is calculated from the
modification time of the file.

=head1 BUGS

This is slow: it calls aggregate twice with force which took 2 x 10-20 seconds on PAUSE.

=cut


use strict;
use warnings;

use File::Find qw(find);
use lib "/home/k/sources/rersyncrecent/lib";
use File::Rsync::Mirror::Recent;
use File::Spec;
use Getopt::Long;
use Pod::Usage qw(pod2usage);

our %Opt;
GetOptions(\%Opt,
           @opt,
          ) or pod2usage(1);

if ($Opt{help}) {
    pod2usage(0);
}

my $aggregate_only = 0;
if (@ARGV == 1) {
    if ($Opt{force}) {
        $aggregate_only=1;
    } else {
        pod2usage(1);
    }
} elsif (@ARGV >= 3) {
    pod2usage(1);
}

my($principal,$file,$epoch) = @ARGV;
my $recc = File::Rsync::Mirror::Recent->new
    (local => $principal);
my($rf) = $recc->principal_recentfile;
my $abs_file = File::Spec->catfile($rf->localroot,$file);

unless ($aggregate_only) {
    unless (defined $epoch) {
        if ($Opt{delete}) {
            my $news = $recc->news(contains => { path => $file });
            if (@$news) {
                print "Found file:\n", YAML::Syck::Dump $news;
                $epoch = $news->[0]{epoch} + 1;
            } else {
                die "didn't find '$file' in this recentfile collection";
            }
        } else {
            my(@stat) = stat $abs_file or die "Could not stat '$abs_file': $!";
            $epoch = $stat[9];
        }
    }
    my $type = $Opt{delete} ? "delete" : "add";
    $rf->update($abs_file,$type,$epoch);
}
warn localtime()." starting first aggregate\n";
$rf->aggregate(force => 1);
warn localtime()." starting second aggregate\n";
$rf->aggregate(force => 1);
warn localtime()." finished\n";


__END__


# Local Variables:
# mode: cperl
# coding: utf-8
# cperl-indent-level: 4
# End:
