#!/usr/bin/perl

BEGIN {
    die "Do not run this as root" unless $>;
    $ENV{DBICDH_DEBUG} = 1;
}

=head1 NAME

amusewiki-upgrade-db - automatic db upgrade for amusewiki

=head1 SYNOPSIS

  amusewiki-upgrade-db

Upgrade the amusewiki database if needed.

=head1 Development option

=over 4

=item --prepare

Prepare the DDLs in the C<ddl> path.

=back

=head1 Procedure

There are 3 cases

=over 4

=item New install from install.pl

This is not a problem, version storage is installed right away. We
have to call prepare_install for each version, though.

  [DBICDH] [info] installing version 4
  [DBICDH] [info] deploying version 4
  [DBICDH] [debug] Running SQL from /home/melmoth/amw/AmuseWikiFarm/script/../dbicdh/SQLite/deploy/4/001-auto-__VERSION.sql
  [DBICDH] [debug] Running SQL from /home/melmoth/amw/AmuseWikiFarm/script/../dbicdh/SQLite/deploy/4/001-auto.sql
  [DBICDH] [debug] Adding database version 4

=item  Upgrade from versioned schema.

Also not a problem. Should go as expected. If it doesn't work, it's a bug

=item Upgrade from old schemas, not versioned.

We have to set manually the schema at version 2, and hope that the
user applied all the previous sql files.

This is what is going to happen, provided that the files are in place:

  $ script/dh-upgrade
  Version storage is not installed, installing, and setting version to 2
  [DBICDH] [info] installing_resultsource __VERSION, version 2
  [DBICDH] [debug] Running SQL from /home/melmoth/amw/AmuseWikiFarm/script/../dbicdh/SQLite/deploy/2/001-auto-__VERSION.sql
  [DBICDH] [debug] Adding database version 2
  [DBICDH] [info] backing up
  [DBICDH] [info] upgrading
  [DBICDH] [info] upgrade_single_step'ing [
    2,
    3
  ]
  [DBICDH] [debug] Running SQL from /home/melmoth/amw/AmuseWikiFarm/script/../dbicdh/SQLite/upgrade/2-3/001-auto.sql
  [DBICDH] [debug] Adding database version 3
  [DBICDH] [info] upgrade_single_step'ing [
    3,
    4
  ]
  [DBICDH] [debug] Running SQL from /home/melmoth/amw/AmuseWikiFarm/script/../dbicdh/SQLite/upgrade/3-4/001-auto.sql
  [DBICDH] [debug] Adding database version 4


=back

=cut

use strict;
use warnings;
# use lib 'lib';
use AmuseWikiFarm::Schema;
use AmuseWikiFarm::Utils::Paths;
use DBIx::Class::DeploymentHandler;
use Getopt::Long;
use Data::Dumper;
use Pod::Usage;
use Try::Tiny;
my ($prepare);

my $help;

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

if ($help) {
    pod2usage();
}


my $schema = AmuseWikiFarm::Schema->connect('amuse')
  or die "Couldn't connect to amuse DB!";

$schema->storage->ensure_connected or die "Couldn't connect to amuse DB!";

# print $schema->storage->sqlt_type, "\n";

# with sqlite, disable the foreign keys, otherwise copying to
# temporary tables fail.

if ($schema->storage->sqlt_type eq 'SQLite') {
    $schema->storage->dbh->do('pragma foreign_keys=off');
}

my $sql_dir = AmuseWikiFarm::Utils::Paths::dbicdh_location();
die "$sql_dir not found" unless $sql_dir->exists;
print "DDLs dir is $sql_dir\n";

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",
                                              force_overwrite => $prepare,
                                             });

# this is not documented because it's for the devels only
# at each bump we do a prepare step.
if ($prepare) {
    $dh->prepare_install;
    # this happens only to create the version 2, hopefully
    unless ($dh->version_storage_is_installed) {
        $dh->install_version_storage({ version => $dh->schema_version });
        $dh->add_database_version({ version => $dh->schema_version - 1});
    }
    $dh->prepare_upgrade;
    exit;
}

unless ($dh->version_storage_is_installed) {
    print "Version storage is not installed, installing, and setting version to 2\n";
    $dh->install_version_storage({ version => 2 });
    $dh->add_database_version({ version => 2 });
}

print "Checking if database is up-to-date: ";
if ($dh->schema_version > $dh->database_version) {
    print "NO, upgrading\n";
    # not supported on Pg...
    # $dh->backup;
    $dh->upgrade;
}
else {
    print "YES\n";
}
