#!/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 AmuseWikiFarm::Utils::Paths;
use Data::Dumper;
use Try::Tiny;
use Cwd;
use Getopt::Long;
use Crypt::XkcdPassword;
use Pod::Usage;

my ($hostname, $mail_notify, $help);
my $site_id = 'amw';
my $password = Crypt::XkcdPassword->new(words => 'IT')->make_password(5, qr{\A[0-9a-zA-Z]{3,}\z});
my $username = "amusewiki";
my $create_db_only;

GetOptions(
           'hostname=s' => \$hostname,
           'username=s' => \$username,
           'password=s' => \$password,
           'email=s' => \$mail_notify,
           'create-db-only' => \$create_db_only,
           help => \$help,
          ) or die;

=head1 NAME

amusewiki-create-doc-site - create an amusewiki sample site and archive

=head1 SYNOPSIS

  amusewiki-create-doc-site

Try to clone the repository of amusewiki.org, creating an initial site
with with documentation and a root user as well, so you are able to
login and create new sites/users from there.

It needs to be called from the application root directory, from where
both the web-server and the jobber should start.

It creates all the needed directories, but it needs to be able to
connect to the database. This means that you need to have dbic.yaml in
the current directory, or in ~/.dbic.yaml with the C<amuse> stanza
with the database settings.

=head2 OPTIONS

=over 4

=item --hostname

Defaults to C<amusewiki.`hostname -d`>

=item --username

The root user. Its name defaults to amusewiki

=item --password

The root user's password. Automatically generated if not provided.

=item --email

Optional (without it, no notification are sent on this site)

=back

=cut

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



unless ($hostname) {
   $hostname = `hostname -d` || 'localdomain';
   chomp $hostname;
   $hostname = 'amusewiki.' . $hostname;
}


# load the db

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

die "Couldn't load the schema! Please check dbic.yaml!\n" unless $schema->storage->dbh;

my $sql_dir = AmuseWikiFarm::Utils::Paths::dbicdh_location();
die "$sql_dir not found" unless $sql_dir->exists;

my $dh = DBIx::Class::DeploymentHandler->new({
                                              schema => $schema,
                                              databases => [qw/SQLite MySQL PostgreSQL/],
                                              sql_translator_args => {
                                                                      add_drop_table => 0,
                                                                      quote_identifiers => 1,
                                                                     },
                                              script_directory => "$sql_dir",
                                             });

$dh->install;

exit if $create_db_only;

# create the needed directories
foreach my $dir (qw/repo opt xapian bbfiles cronjobs opt ssl staging log/) {
     unless (-d $dir) {
        mkdir $dir or die "Cannot create $dir!";
    }
}

if (my @sites = $schema->resultset('Site')->all) {
    die "There are already sites in this database, aborting\n";
}

if (my @users = $schema->resultset('User')->all) {
    die "There are already user in this database, aborting\n";
}

if ($hostname =~ m/^\s*([a-z0-9-]+(\.[a-z0-9-]+)*)\s*$/) {
    $hostname = $1;
}
else {
    die "Host name $hostname doesn't look valid\n";
}
if ($site_id =~ m/\A\s*([1-9a-z][0-9a-z]{1,15})\s*\z/) {
    $site_id = $1;
}
else {
    die "Site code contains illegal characters\n";
}

if ($username =~ m/\s*([a-z0-9]+)\s*/) {
    $username = $1;
}
else {
    die qq{Bad username "$username"\n};
}

unless ($password =~ m/\A[[:ascii:]]+\z/) {
    die qq{Bad password, non ascii\n};
}

my $site = $schema->resultset('Site')->create({
                                               id => $site_id,
                                               canonical => $hostname,
                                               sitename => "AmuseWiki documentation",
                                               secure_site => 0,
                                               pdf => 0, # no pdfs for this, speed up
                                               mail_notify => $mail_notify || '',
                                              });
$site->discard_changes;
my $repo_root = $site->repo_root;

unless (-d $repo_root) {
    if ((system(git => clone => "https://amusewiki.org/git/amw" => $site->repo_root) == 0) or
        (system(git => clone => "https://github.com/melmothx/amusewiki-site.git" => $site->repo_root) == 0)) {
        print "Repository with the official documentation has been created at " . $site->repo_root . "\n";
        $site->configure_cgit;
    }
    elsif ($site->initialize_git) {
        print "An stub repository has been created at " . $site->repo_root . "\n";
    }
    else {
        die "This shouldn't happen";
    }
}
# compile
$site->update_db_from_tree(sub { });

my $user = $schema->resultset('User')->create({
                                               username => $username,
                                               password => $password,
                                              });
$user->set_roles([{ role => 'root' }]);
$site->add_to_users($user);

print <<"EOF";
Summary of the initial setup:

Host: "$hostname"
Site ID: "$site_id"
Root username: "$username"
Root password: "$password"

You should be able to login at http://$hostname/login with the above
credentials. This is going to be a dummy site with the documentation.

You can create a new site at http://$hostname/admin/sites

If your browser can't find the server or shows you a default nginx
page, please edit the /etc/hosts file on the browser's machine,
setting the IP for "$hostname":

E.g.

# local install, i.e. browser machine is the same as the server
127.0.0.1 localhost $hostname

# remote install. On the machine you are using (the client, the
# browser's machine), point to the server's IP

1.2.3.4 $hostname

EOF
