#!/usr/bin/perl
use warnings;
use strict;

our $VERSION = 'v1.4.5';

use FindBin;
use lib "$FindBin::Bin/../lib/perl5";
use Narada::Config qw( get_config_line );
use DBI;

use constant SCHEME => 'var/sql/db.scheme.sql';

main(@ARGV) unless caller;  ## no critic (ProhibitPostfixControls)

sub err {   ## no critic (ProhibitBuiltinHomonyms)
    die "narada-setup-mysql: @_\n";
}

sub main {
    die "Usage: narada-setup-mysql [--clean]\n"
        if (@_ >  1)
        || (@_ == 1 && $_[0] ne '--clean');

    my $db = get_config_db() or return;
    $::dbh = DBI->connect($db->{dsn_nodb}, $db->{login}, $db->{pass},
        {RaiseError=>1}) or err DBI->errstr;

    if (@_) {
        $::dbh->do('DROP DATABASE IF EXISTS `'.$db->{db}.q{`});
    }
    else {
        $::dbh->do('CREATE DATABASE IF NOT EXISTS `'.$db->{db}.q{`});
        $::dbh->do('USE `'.$db->{db}.q{`});
        if (0 < $::dbh->prepare('SHOW TABLES')->execute()) {
            err 'SQL files not imported because database does not empty';
        }
        if (-f SCHEME) {
            import_sql(SCHEME);
            for (grep {-f $_ && $_ ne SCHEME} glob 'var/sql/*.sql') {
                import_sql($_);
            }
        }
    }

    return;
}

sub get_config_db {
    my %db;
    $db{db} = eval { get_config_line('db/db') };
    if (!defined $db{db} || !length $db{db}) {
        return;
    }
    $db{login}= get_config_line('db/login');
    $db{pass} = get_config_line('db/pass');
    $db{host} = eval { get_config_line('db/host') };
    $db{port} = eval { get_config_line('db/port') };
    $db{dsn_nodb}  = 'dbi:mysql:';
    $db{dsn_nodb} .= ';host='.$db{host} if $db{host}; ## no critic
    $db{dsn_nodb} .= ';port='.$db{port} if $db{port}; ## no critic
#    $db{dsn} = $db{dsn_nodb}.';database='.$db{db};
    return \%db;
}

sub import_sql {
    my ($file) = @_;
    warn "importing $file...\n";
    system("narada-mysql <\Q$file\E") == 0 or err 'failed to import '.$file;
    return;
}


1; # Magic true value required at end of module
__END__

=encoding utf8

=head1 NAME

narada-setup-mysql - initialize project database


=head1 VERSION

This document describes narada-setup-mysql version v1.4.5


=head1 USAGE

    narada-setup-mysql [--clean]


=head1 DESCRIPTION

Initialize/drop your Narada project's MySQL database.

If "config/db/db" absent or empty do nothing.

When executed without params will create database (if needed) and load sql dumps
into database (if C<var/sql/db.scheme.sql> exist).

When executed with --clean option will drop project's database with all tables.

Script must be executed only from "project root directory".


=head1 CONFIGURATION AND ENVIRONMENT

narada-setup-mysql use these configuration files:

    config/db/db
    config/db/login
    config/db/pass
    config/db/host
    config/db/port

Database initialized using these files (db.scheme.sql must exist and will
be loaded first, other files will be loaded in undefined order):

    var/sql/db.scheme.sql
    var/sql/*.sql


=head1 SUPPORT

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the issue tracker
at L<https://github.com/powerman/Narada/issues>.
You will be notified automatically of any progress on your issue.

=head2 Source Code

This is open source software. The code repository is available for
public review and contribution under the terms of the license.
Feel free to fork the repository and submit pull requests.

L<https://github.com/powerman/Narada>

    git clone https://github.com/powerman/Narada.git

=head2 Resources

=over

=item * MetaCPAN Search

L<https://metacpan.org/search?q=Narada>

=item * CPAN Ratings

L<http://cpanratings.perl.org/dist/Narada>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Narada>

=item * CPAN Testers Matrix

L<http://matrix.cpantesters.org/?dist=Narada>

=item * CPANTS: A CPAN Testing Service (Kwalitee)

L<http://cpants.cpanauthors.org/dist/Narada>

=back


=head1 AUTHOR

Alex Efros E<lt>powerman@cpan.orgE<gt>


=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2008-2015 by Alex Efros E<lt>powerman@cpan.orgE<gt>.

This is free software, licensed under:

  The MIT (X11) License


=cut