#!/usr/bin/php
<?php
$password = $argv[3];
$host = $argv[1];
$user = $argv[2];
if (!$password)
{
    echo "pty_mysql_backup_all_each_db_each_table 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 php ./pty_mysql_backup_all_each_db_each_table.php <HOST> <USERNAME> <PASSWORD>>\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];

    # performance_schema, information_schema 는 백업 무시
    if ($dbName == "performance_schema" || $dbName == "information_schema")
        continue;

    echo "====================================\ndatabase = $dbName\n====================================\n";

    $sql = "SHOW TABLES FROM `$dbName`";
    $result = mysqli_query($connection, $sql);

    if (!$result) {
        echo "DB Error, could not list tables\n";
        echo 'MySQL Error: ' . mysqli_error($connection);
        exit;
    }

    while ($row = mysqli_fetch_row($result)) {
        $tableName = $row[0];
        mysql_backup($host, $user, $password, $dbName, $tableName);
    }
}


echo "finished\n";

function mysql_backup($host, $user, $password, $dbName, $tableName)
{
	if (strpos($dbName, "x_") === 0)
		return;

	mkdir ("$dbName");
    $cmd = "mysqldump -u $user -p$password -h $host $dbName $tableName --default-character-set=utf8mb4 --routines --events --add-drop-table --add-drop-database --complete-insert --extended-insert=TRUE --single-transaction > {$dbName}/{$tableName}.sql";
    echo "{$cmd}\n";

    system($cmd);
}

?>
