#!/usr/bin/perl

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

use Parallel::ForkManager;
use Term::ANSIColor qw(:constants);
use List::MoreUtils qw(first_index);
use Digest::MD5 qw(md5 md5_hex md5_base64);

use lib '/app/tools/common/lib';
use Common::Session;
use Common::DB::Diff::Table;
use Common::DB::Diff::Database;

my ( $opt, $usage ) = clopt(
    [ 'help|?|h'     => "print usage message and exit", { 'implies' => { 'database' => 1 } } ],
    [ 'database|d=s' => 'Database to compare' ],
    [ 'table|t=s'    => 'Table to verify' ],
    [ 'primary|p=s'  => 'Primary DB default: db01',  { 'default' => 'db01' } ],
    [ 'replica|r=s'  => 'Replicat DB default: db02', { 'default' => 'db02' } ],
);

if ( $opt->help ) {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

my $primary = $opt->primary;
my $replica = $opt->replica;

my $p_dbh = Common::Session::getdbh($primary);
my $r_dbh = Common::Session::getdbh($replica);

my $dbx = Common::Session::getdbx('admindb');

## get all database diffs
my $search = { 'is_diff' => 'Y' };
if ( defined $opt->database ) {
    $search->{'dbname'} = $opt->database;
    if ( defined $opt->table ) {
        $search->{'tabname'} = $opt->table;
    }
}

my $rset = $dbx->resultset('Report::SysDbReplicaDiff')->search($search);
while ( my $row = $rset->next ) {
    my $min = $row->minrow;
    my $max = $row->maxrow;
    my $db  = $row->dbname;
    my $tab = $row->tabname;
    my $key = $row->keycol;

    logMessage( 'info', "Verifying $db.$tab [$key] min: $min max: $max" );

    my $tdiff = Common::DB::Diff::Table->new( $db, $tab, $primary, $replica );

    my ( $err, $msg, $minrow, $maxrow, $pcnt, $rcnt ) = $tdiff->compare_signatures( $min, $max, $p_dbh, $r_dbh );
    if ($err) {
        logMessage( 'info', "$msg - verified" );
    } else {
        logMessage( 'info', "$db.$tab [$key] min: $min max: $max - ok - removing..." );
        $row->delete;
    }

}
