#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use Text::CSV::Easy(qw/csv_build csv_parse/);

use lib '/app/tools/common/lib';
use Common::Session;

my ( $opt, $usage ) = clopt(
    [ 'host|h=s'   => 'DBHost to migrate', { 'required' => 1 } ],
    [ 'schema|s=s' => 'Schema to restore', { 'default'  => 'all' } ],
    [ 'help|?'     => "print usage message and exit" ]
);
logMessage( 'info', $usage->text, 'options' ), exit if $opt->help;

my $dbh  = Common::Session::getdbh( $opt->host );
my $rows = $dbh->selectcol_arrayref(
    qq{
SELECT 
   db.schema_name 
FROM 
    information_schema.schemata db 
WHERE 1 
    AND db.schema_name NOT IN (
	    'information_schema',
        'mysql',
        'percona',
        'performance_schema',
        'restore',
        'sys'
    )
}
);
my $rules;
my $i = 0;
foreach my $db ( @{$rows} ) {
    if ( $opt->schema ) {
        next if not $db ne $opt->schema;
    }
    push @{ $rules->{'rules'} },
      {
        'rule-type'      => 'selection',
        'rule-id'        => ++$i,
        'rule-name'      => $i,
        'rule-action'    => 'include',
        'object-locator' => {
            'schema-name' => $db,
            'table-name'  => "%"
        }
      };
}
my $json = prettyEncode($rules);
print $json;
