#!/usr/bin/perl

BEGIN { die "Do not run this as root" unless $>; }
use utf8;
use strict;
use warnings;
# use lib 'lib';
use AmuseWikiFarm::Schema;
use AmuseWikiFarm::Archive::OAI::PMH;
use File::Temp;
use YAML qw/LoadFile DumpFile/;
use Getopt::Long;
use Pod::Usage;
use Time::HiRes qw/gettimeofday tv_interval/;

my ($help, $all);
GetOptions(help => \$help,
           all => \$all) or die;

my @site_ids = @ARGV;

if ($help) {
    pod2usage;
    exit 2;
}

my $search = undef;
if (@site_ids) {
    $search = { id => \@site_ids };
}
elsif (!$all) {
    pod2usage;
    exit 2;
}

my $schema = AmuseWikiFarm::Schema->connect('amuse');

foreach my $site ($schema->resultset('Site')->search($search, { order_by => 'id' })) {
    my $start = [ gettimeofday ];
    my $oai_pmh = AmuseWikiFarm::Archive::OAI::PMH->new(site => $site,
                                                        logger => sub {
                                                            my @lines = @_;
                                                            foreach my $l (@lines) {
                                                                print tv_interval($start) . " " . $l;
                                                            }
                                                        },
                                                       );
    my $time = time();
    $oai_pmh->update_site_records({ refresh => 1 });
    print "Updated OAI-PMH records for " . $site->id . " in " . (time() - $time) . " seconds\n";
}


=pod

=encoding utf8

=head1 NAME

amusewiki-oai-pmh-index - Rebuild the OAI-PMH index

=head1 SYNOPSIS

 amusewiki-oai-pmh-index [ --all |  site_id_1 [ site_id_2 site_id_3 ...] ]

=cut


