#!/usr/local/bin/perl
# $Id: mwExport,v 1.2 2007/05/18 23:42:25 ask Exp $
# $Source: /opt/CVS/Modwheel/utils/mwExport,v $
# $Author: ask $
# $HeadURL$
# $Revision: 1.2 $
# $Date: 2007/05/18 23:42:25 $
use strict;
use warnings;
use Data::Dumper;
use Getopt::Euclid;
use Perl6::Form;
use Params::Util qw(_CODELIKE);
use IO::Interactive qw(is_interactive interactive);
use Modwheel::Session;
use Term::ANSIColor;
use Readonly;
use YAML::Syck;
use JSON::Syck;
use namespace::clean;
use version; our $VERSION = qv('0.3.2');


# Euclid seems to break is_interactive, we clear out @ARGV,
# so noone thinks that we're reading from a file.
undef @ARGV;

my $prefix     = $ARGV{-prefix};
my $configfile = $ARGV{-config};
my $site       = $ARGV{-site};
$prefix      ||= '/opt/modwheel';
$configfile  ||= 'config/modwheelconfig.yml';

my $modwheel_config = {
    prefix          => $prefix,
    configfile      => $configfile,
    debug           => 0,
};
if ($site) {
    $modwheel_config->{site} = $site;
}

Readonly our $Bold  => color 'bold';
Readonly our $Reset => color 'reset';

our($modwheel, $user, $db, $object, $repository, $template)
    = modwheel_session($modwheel_config,
    qw(db user object template repository));

our %COMMANDS = (
    quit        => sub {
        exit;
    },
    version     => sub {
        say $VERSION;
    }

);


$db->connect( );

use YAML::Syck;
use JSON::Syck;
my @data;
my $slurp;
my $in_start = 1;
open EXPORT, './export' or die;
while (my $line  = <EXPORT> ) {
    if (!$in_start && $line =~ m/^---\s+$/xms) {
        push @data, YAML::Syck::Load($slurp);
        $slurp = q{};
    }
    $slurp .= $line;
    $in_start = 0;
}

$^W =0;
foreach my $cur (@data) {
    delete $cur->{id};
    my $newo = Modwheel::Object->new({modwheel=>$modwheel, user=>$user,
db=>$db});
    $newo->deserialize( JSON::Syck::Dump($cur) );
    print $newo->save( ), "\n"; 
}

exit;
=cut


my $buffer;
while (my $line  = safeprompt("${Bold}sql>${Reset} ")) {
    $buffer .= $line;
    if ($line =~ m/;\s*$/xms) {
        my $valid_cmd = do_command($buffer);
        if (!$valid_cmd) {
            do_query($buffer);
        }
        # clear buffer.
        $buffer = q{};
    }
}
# execute anything left in buffer.
if (length $buffer) {
    do_query($buffer);
}

$db->disconnect( );

sub do_query {
    my ($query) = @_;
    $query = $db->trim($query);
    return if not $query;
    my $sth = $db->prepare($query);
    return if not $sth;
    my $ret = $db->execute($sth);
    return if not $ret;
    if ($sth->rows) {
        my @rows;
        while (my $hres = $db->fetchrow_hash($sth)) {
            push @rows, $hres;
        }
        print $ARGV{-json} ? JSON::Syck::Dump(\@rows)
                           : YAML::Syck::Dump(\@rows);
    }
    $query =~ s{ ;$}{}xms;
    print "${Bold}++${Reset} $query\n";
    print "${Bold}++ OK${Reset}\n";
    $db->query_end($sth);
    return;
}

sub do_command {
    my ($line) = @_;
    $line =~ tr/;//d;
    $line = $db->trim($line);
    my ($command, @args) = split m/\s+/xms, $line;
    my $cmd_sub_ref = $COMMANDS{$command};
    if (_CODELIKE($cmd_sub_ref)) {
        $cmd_sub_ref->(@args);
        return 1;
    }
    return 0;
}

sub safeprompt {
    print {interactive} @_;
    my $reply = <STDIN>;
    $reply =~ s/\n/ /xms;

# We dont use chomp, because we must have a character
# left so 'while' knows we're not finished yet.

    return $reply;
}

sub say { return print {interactive} @_, "\n"};

__END__

=pod

=head1 NAME

mwsql - Execute SQL using Modwheel database drivers.

=head1 VERSION

This documentation refers to Modwheel version 0.3.2

=head1 USAGE

    mwsql [options] 

=head1 REQUIRED ARGUMENTS

One of the COMMANDS listed below.

=head1 OPTIONS

=head2 COMMANDS

=over

=head2 OPTIONAL SETTINGS

=item -p[refix] <prefix>

Set the prefix for Modwheel.
Default: /opt/modwheel

=item -c[onfig] <configfile>

Use a different modwheel configfile than the default.
Default: $PREFIX/config/modwheelconfig.yml

=item -s[ite] <site>

Use a different modwheel site than the default.
Default: defaultsite set in the config file.

=item -j[son]

Use JSON instead of YAML for dumping data.

=item -logmode <logmode>

Use a logging mode other than stderr. (i.e off)
Default: stderr

=back

=head1 DESCRIPTION

Execute SQL using Modwheel database drivers.

=head1 DIAGNOSTICS


Check that mwsql is using the right configuration file, and the right prefix.
Set them manually with -prefix and -configfile.

=head1 CONFIGURATION 

mwsql is dependant on a Modwheel configuration file and database.
See L<Modwheel::Manual::Config> and L<Modwheel::Manual> for more information.

=head1 EXIT STATUS

As the program is interactive, you should not depend on the exit statis
of this application in any script.

=head1 DEPENDENCIES

=over 4

=item Modwheel

=item Getopt::Euclid

=item IO::Prompt

=item Params::Util

=item Perl6::Form

=item Term::ANSIColor

=item Readonly

=back

=head1 INCOMPATIBILITIES

None known.

=head1 BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to
C<bug-modwheel@rt.cpan.org>, or through the web interface at

=head1 SEE ALSO

=over 4

=item * L<Modwheel::Manual>

The Modwheel manual.

=item * L<http://www.0x61736b.net/Modwheel/>

The Modwheel website.

=back

=head1 VERSION

v0.3.2

=head1 AUTHOR

Ask Solem, C<< ask@0x61736b.net >>.


=head1 LICENSE AND COPYRIGHT

Copyright (c), 2007 Ask Solem C<< ask@0x61736b.net >>.

All rights reserved.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.6 or,
at your option, any later version of Perl 5 you may have available.

=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE
SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE
STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE
SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE,
YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE
SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO
LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER
SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

=cut

