#!/usr/bin/perl

BEGIN { die "Do not run this as root" unless $>; }

use strict;
use warnings;
use Cwd;
# use lib 'lib';
use File::Basename;
use File::Find;
use File::Spec::Functions qw/catdir/;
use Data::Dumper;
use AmuseWikiFarm::Schema;
use POSIX qw/nice/;
use Getopt::Long;
use Pod::Usage;

my ($refresh, $recompile, $help, $xapian,
    $rebuild);

GetOptions (refresh => \$refresh,
            help => \$help,
            xapian => \$xapian,
            rebuild => \$rebuild,
           ) or die;

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

=pod

=encoding utf8

=head1 NAME

amusewiki-bootstrap-archive - bootstrap amusewiki archives

=head1 SYNOPSIS

Usage: amusewiki-bootstrap-archive [ --refresh | --recompile | --xapian | --help ] [ <site-id>, <site-id-2>, ... ]

The list of site ids is optional. If not passed, all the sites will be built.

You need to be in the root directory of the application, i.e. where
'repo' is located.

=head2 OPTIONS

Without any option, bootstrap the text database and the build the
files which need compilation.

=over 4

=item --help

Print this help and exit.

=item --refresh

Same as without options, but checking for outdated files in the
database first. You can save a lot of I/O.

=item --xapian

Do not perform any compilation or db operation, but only reindex the
xapian database.

=item --rebuild

Rebuild all the formats. It does the same thing as calling the
/tasks/rebuild route.

=back

=cut

# be nice
nice(19);

binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';

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

die "No repo directory found in the current directory. Are you in the application home?\n"
  unless -d 'repo';

my @codes;
if (@ARGV) {
    @codes = @ARGV;
}
else {
    @codes = map { $_->id } $schema->resultset('Site')->all;
}

foreach my $code (@codes) {
    my $site = $schema->resultset('Site')->find($code);
    if ($site) {
        print "Processing $code\n";
    }
    else {
        warn "Site code $code not found in the database. Skipping...\n";
        next;
    }
    # with --refresh, just check
    if ($refresh) {
        $site->bootstrap_archive({ logger => sub { print @_ } });
    }
    elsif ($xapian) {
        $site->xapian_reindex_all(sub { print @_ });
    }
    elsif ($rebuild) {
        $site->bulk_jobs->rebuilds->active_bulk_jobs->abort_all;
        my $j = $site->rebuild_formats;
        print $site->canonical_url . '/tasks/job/' . $j->bulk_job_id . "/show\n";
    }
    # without, do a full import
    else {
        $site->bootstrap_archive({ full => 1, logger => sub { print @_ } });
    }
}
