#!/usr/bin/perl

BEGIN {
    die "Do not run this as root" unless $>;
    $ENV{DBICDH_DEBUG} = 1;
}
use strict;
use warnings;
use utf8;
# use lib 'lib';
use DBIx::Class::DeploymentHandler;
use AmuseWikiFarm::Schema;
use Getopt::Long;
use YAML qw/DumpFile LoadFile/;
use Data::Dumper;
use Path::Tiny;
use File::Copy::Recursive qw/dircopy/;
use Pod::Usage;

my ($import_site, $export_site, $working_dir, $help);

GetOptions(
           'export|e=s' => \$export_site,
           'import|i=s' => \$import_site,
           'working-directory|d=s' => \$working_dir,
           'help|h' => \$help,
          ) or die;

=head1 NAME

amusewiki-bookcover - export/import bookcovers across sites/instances

=head1 SYNOPSIS

 amusewiki-bookcover --export SITE-ID --working-directory EXPORT-DIR

 amusewiki-bookcover --import SITE-ID --working-directory IMPORT-DIR

The import and export options are mutually exclusive.

The working directory will be created by the export and consumed by
the import.

=head2 OPTIONS

=over 4

=item --help

Show this help and exit.

=item --working-directory DIRECTORY

Mandatory. The import will consume the directory produced by the
export (so you can copy that over to other server and import the
bookcovers there, or on the same server if you want to copy the
bookcovers across sites).

=item --export SITE-ID

Export the site's bookcovers in the working directory.

=item --import SITE-ID

Perform an import of the bookcovers in the working directory into the
site with this ID.

=back

=cut

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

if ($import_site && $export_site) {
    die "--import and --export are mutually exclusive"
}
die "Missing --working-directory option" unless $working_dir;

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

my $wd = path($working_dir);
$wd->mkpath;

my @bc_fields = (qw/
                       title
                       coverheight
                       coverwidth
                       spinewidth
                       flapwidth
                       wrapwidth
                       bleedwidth
                       marklength
                       foldingmargin
                       template
                       font_name
                       language_code
                       comments
                       created
                   /
                );
my @tk_fields = (qw/
                       token_name token_value sorting_pos
                   /);


if ($export_site) {
    if (my $site = $schema->resultset('Site')->find($export_site)) {
        foreach my $bc ($site->bookcovers) {
            my %dbdata = $bc->get_columns;
            my %data = map { $_ => $dbdata{$_} } @bc_fields;
            my @tokens;
            foreach my $token ($bc->bookcover_tokens) {
                push @tokens, { map { $_ => $token->$_ } @tk_fields };
            }
            $data{tokens} = \@tokens;
            $data{username} = $bc->username;
            # print Dumper \%data;
            DumpFile($wd->child($bc->bookcover_id . '.yaml')->stringify, \%data);
            dircopy($bc->working_dir->stringify, $wd->child($bc->bookcover_id)->stringify);
        }
        print "$export_site left in $wd\n";
    }
}
if ($import_site) {
    if (my $site = $schema->resultset('Site')->find($import_site)) {
        foreach my $file ($wd->children(qr/\.yaml$/)) {
            my $sourcedir = $wd->child($file->basename(qr/\.yaml/));
            if ($sourcedir->exists) {
                my $data = LoadFile("$file");
                my @tokens = @{ delete $data->{tokens} };
                if (my $username = delete $data->{username}) {
                    if (my $user = $schema->resultset('User')->find({ username => $username })) {
                        print "Assigning to user $username\n";
                        $data->{user_id} = $user->id;
                    }
                }
                my $bc = $site->bookcovers->create($data);
                foreach my $tk (@tokens) {
                    $bc->bookcover_tokens->create($tk);
                }
                my $bcwd = $bc->working_dir;
                print "Creating $bcwd from $sourcedir\n";
                dircopy("$sourcedir", "$bcwd");
            }
            else {
                print "$sourcedir does not exist\n";
            }
        }
    }
}

