#!/usr/bin/php
<?php
$password = $argv[1];
$host = $argv[2];
$user = $argv[3];
if (!$password)
{
    echo "pty_mysql_optimize.sh version 1.0\n";
    echo "Copyright (C) 2019 by cpueblo, PlatyHouse Co.,LTD.\n";
    echo "Web site: https://www.platyhouse.com/\n\n";
    echo "Usage ./pty_mysql_optimize.sh <MYSQL ROOT PASSWORD> <HOST (default: localhost)> <USERNAME (default: root)> \n";
    exit;
}

if (!$host)    $host = "localhost";
if (!$user)    $user = "root";

$connection = mysqli_connect($host, $user, $password);
if (!$connection) {
    die ('Could not connect database.' . mysqli_error()."\n");
}

$databases = mysqli_query($connection, "SHOW databases");
while ($databaseInfo = mysqli_fetch_array($databases)) { // go through each row that was returned in $result
    $dbName = $databaseInfo[0];

    if ($dbName == "performance_schema")
        continue;

    if ($dbName == "mysql")
        continue;

    if ($dbName == "sys")
        continue;

    if ($dbName == "information_schema")
        continue;


    echo "====================================\ndatabase = $dbName\n====================================\n";
    mysql_innodb_defragment($host, $user, $password, $dbName);
}

echo "finished\n";
mysqli_close($connection);


function mysql_innodb_defragment($host, $user, $password, $dbName)
{
    $connection = mysqli_connect($host, $user, $password);
    if (!$connection) {
        die ('Could not connect:' . mysql_error());
    }

    mysqli_select_db($connection, $dbName);


    $showtables = mysqli_query($connection, "SHOW TABLES FROM `{$dbName}`");

    while ($tableInfo = mysqli_fetch_array($showtables)) { // go through each row that was returned in $result

        $tableName = $tableInfo[0];
        echo("table = {$tableName} \n");    // print the table that was returned on that row.

        $n = mysqli_query ($connection, "SHOW TABLE STATUS FROM `{$dbName}` WHERE `Name` = '{$tableName}'");
        $tableStatus = mysqli_fetch_array($n);

        echo "checking table.\n";
        mysqli_query ($connection, "CHECK TABLE `{$tableName}`");

        if ($tableStatus['Engine'] == "InnoDB") {
            echo "alter table.\n";
            mysqli_query($connection, "ALTER TABLE `{$tableName}` ENGINE=InnoDB");
        }
        else
        {
            echo "alter table passed. engine = {$tableStatus['Engine']}\n";
        }

        echo "analyze table.\n";
        mysqli_query ($connection, "ANALYZE TABLE `{$tableName}`");

        echo "optimize table.\n";
        mysqli_query ($connection, "OPTIMIZE TABLE `{$tableName}`");

        echo "flush table.\n";
        mysqli_query ($connection, "FLUSH TABLE `{$tableName}`");

        echo "\n";
    }

    mysqli_close($connection);
}


?>
