#!/usr/bin/perl

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

=head1 NAME

amusewiki-import-redirections - Import redirections for a site from a YAML file

=head1 SYNOPSIS

  amusewiki-import-redirections <site-id> <file.yaml>

The script is handy for site migrations into amusewiki to keep the old
urls working.

=head1 FORMAT

The file.yaml is expected to be a dump of an hashref were the key is
the legacy path, and the value the new path.

E.g.

  ---
  /2006/12/post.html: /library/post-from-2006
  /2007/02/post.html: /library/post-from-2007


=cut

use strict;
use warnings;
# use lib 'lib';
use AmuseWikiFarm::Schema;
use YAML qw/LoadFile/;

my ($id, $file) = @ARGV;
die "Missing site id" unless $id;

my $schema = AmuseWikiFarm::Schema->connect('amuse');
my $site = $schema->resultset('Site')->find($id);
die "$id not found" unless $site;

my $redirections = LoadFile($file);

foreach my $old (sort keys %$redirections) {
    my $new = $redirections->{$old};
    $site->search_related('legacy_links')->update_or_create({
                                                             legacy_path => $old,
                                                             new_path => $new,
                                                            });
}
