#!/usr/bin/perl

use constant 'PERCENTUSED' => .8;

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

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

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

my $sql = (
    qq{
SELECT
	c.table_schema,
	c.table_name,
	c.column_name,
	c.data_type,
	IF(c.column_type LIKE '%unsigned',1,0) is_unsigned,
	CASE c.data_type
		WHEN 'tinyint' THEN IF(c.column_type LIKE '%unsigned%',POWER(2,8),POWER(2,7) ) - 1
		WHEN 'smallint' THEN IF(c.column_type LIKE '%unsigned%',POWER(2,16),POWER(2,15) ) - 1
		WHEN 'mediumint' THEN IF(c.column_type LIKE '%unsigned%',POWER(2,24),POWER(2,23) ) - 1
		WHEN 'int' THEN IF(c.column_type LIKE '%unsigned%',POWER(2,32),POWER(2,31) ) - 1
	 	ELSE 0
	END max_id
FROM
	information_schema.columns c
WHERE 1
	AND c.extra = 'auto_increment'
	AND c.data_type != 'bigint'
	AND c.table_schema REGEXP '^C_.*'
ORDER BY 1,2
}
);

my $clients = Common::Session::getclients;
foreach my $host ( sort keys %{ $clients->by_host } ) {
	logMessage('info',"Connecting to $host");
    my $dbh = Common::DB::Connect->connect($host);
    my $data;
    my $rows = $dbh->selectall_arrayref($sql);
    if ($rows) {
        foreach my $row ( @{$rows} ) {
            push @{ $data->{ $row->[0] } }, $row;
        }
    }
    foreach my $schema ( sort keys %{$data} ) {
		logMessage('info',"use $schema;");
        $dbh->do("USE $schema");
        foreach my $tab ( @{ $data->{$schema} } ) {
            my $idsql = "SELECT IFNULL(MAX($tab->[2]),0) maxid FROM $tab->[1];";
            my $max   = $dbh->selectcol_arrayref($idsql)->[0];
			my $percent = $max ? $max / $tab->[5] : $max;
			if ( $percent > .1 ) {
            	my $msg = "$host,$tab->[0],$tab->[1],$tab->[2],$max,$tab->[5],$percent";
				logMessage('warn',$msg);
			}
            if ( $max > $tab->[5] * PERCENTUSED ) {
                my $x;
            }
        }
    }
}
