#!/bin/sh
# In memoriam of my beloved friend and brother in Christ Nikolay Paskalev!
# I hope I'll see you in heaven Niki!
# Licensed under GPL2

php=$(which php);
php_script="/tmp/check-database-size.php";
# change with your database password here and below in the script after the comment // put the mysql password here as well
mysql_pass='mysql_pass';
output_log_file="/root/database_sizes.txt";

if [ -f "$php_script" ]; then
rm -f $php_script; 
fi
cat > $php_script << "EOF"
<?php
//print_r($argv);
function file_size_info($filesize) {
 $bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); # values are always displayed  
 if ($filesize < 1024) $filesize = 1; # in at least kilobytes. 
 for ($i = 0; $filesize > 1024; $i++) $filesize /= 1024;
 $file_size_info['size'] = ceil($filesize);
 $file_size_info['type'] = $bytes[$i];
 return $file_size_info;
}
$db_server = 'localhost';
$db_user = 'root';

// put the mysql password here as well

$db_pwd = 'mysql_pass';
$db_name = "$argv[1]";
$db_link = @mysql_connect($db_server, $db_user, $db_pwd)
 or exit('Could not connect: ' . mysql_error());
$db = @mysql_select_db($db_name, $db_link)
 or exit('Could not select database: ' . mysql_error());
// Calculate DB size by adding table size + index size: 
$rows = mysql_query("show TABLE STATUS");
$dbsize = 0;
while ($row = mysql_fetch_array($rows)) {
 $dbsize += $row['Data_length'] + $row['Index_length'];
}
//print " $dbsize bytes";
//print 'or<br />';
$dbsize = file_size_info($dbsize);
print "Database $argv[1]: {$dbsize['size']} {$dbsize['type']}";
?>

EOF


for i in $(mysql -u root -p"$mysql_pass" -Bse 'show databases'|grep -v "information_schema"); do 
echo "Estimating size of database: $i";
$php $php_script $i >> $output_log_file 2>&1
done
echo
echo "Database list and sizes stored in $output_log_file. Enjoy!";
exit 0;
