<?php

if ( empty( $args[0] ) || empty( $args[1] ) ) {
	WP_CLI::error( 'Usage: wp eval-file convert-tables.php options /path/to/backups 100 0, where 100 is the batch count and 0 is the min blog ID' );
	die;
}

$table_short_name = $args[0];
$backup_dir = $args[1];

$batch_size = isset( $args[2] ) ? (int) $args[2] : 5;
$min_blog_id = isset( $args[3] ) ? (int) $args[3] : 1;
//var_dump( $table_short_name, $backup_dir, $batch_size, $min_blog_id );

global $wpdb;

if ( ! file_exists( $backup_dir ) ) {
	mkdir( $backup_dir );
}

$log_file = $backup_dir . '/convert.log';

$date = date( 'Y-m-d H:i:s' );
file_put_contents( $log_file, "Beginning conversion process at $date\n", FILE_APPEND );

$blog_id = $min_blog_id;
$max_blog_id = $blog_id + $batch_size;
while ( $blog_id < $max_blog_id ) {
	$prefix = $wpdb->get_blog_prefix( $blog_id );
	$table_name = $prefix . $table_short_name;
	$table_exists = $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" );

	$blog_id++;

	if ( ! $table_exists ) {
		file_put_contents( $log_file, "$table_name: Does not exist\n", FILE_APPEND );
		continue;
	}

	// Create backup.
	$backup_file = $backup_dir . '/' . $table_name . '.sql';
	$command = "db export --tables=$table_name $backup_file";

	$backed_up = WP_CLI::runcommand( $command, [
		'return' => 'all',
		'launch' => true,
		'exit_error' => false,
	] );
	if ( 0 !== $backed_up->return_code ) {
		file_put_contents( $log_file, "$table_name: Could not create export\n", FILE_APPEND );
		continue;
	}

	$converted = maybe_convert_table_to_utf8mb4( $table_name );

	if ( $converted ) {
		file_put_contents( $log_file, "$table_name: Converted!\n", FILE_APPEND );
	} else {
		file_put_contents( $log_file, "$table_name: Could not convert.\n", FILE_APPEND );
	}
}
