#!/usr/bin/perl

use strict;
use Data::Dumper;


use constant kBackupPath => '/tmp';


# Generate the path to the place we'll save the db images.
# Then create the directory.
#
my ($d, $m, $y) = (localtime)[3,4,5];
my $path = sprintf("%s/DB_BACKUP_%04d%02d%02d", kBackupPath, (1900 + $y), $m + 1, $d);

mkdir $path or die "ERROR: Can't create directory $path: $! : (Remove directory first if it already exists)\n";



# Get a list of all databases.
#
my @dbNames = _getAllDatabaseNames();

foreach my $dbName (@dbNames)
{
    _backupDatabase($dbName, $path);
}


sub _getAllDatabaseNames
{
    # First, query mysql to get the list of dbs.
    #

    my $dbsRaw = `/usr/bin/mysqlshow -uroot`;

    # Doesn't seem to be a way to get a simple list - so we have to parse the
    # names out from all the extra display frosting this command returns.
    #

    my @dbNames;
    my @lines = split("\n", $dbsRaw);
    
    for (my $i = 0; $i < (scalar @lines) - 1; $i++)
    {
        # First three lines are crap.
        #
        next if $i < 3;

        
        if ($lines[$i] =~ m/\| (\S*) (.*)\|/)
        {
            push @dbNames, $1 unless $1 eq 'mysql';
        }
    }

    return @dbNames;
}


sub _backupDatabase
{
    my ($dbName, $path) = @_;

    # Create filename
    #
    my $filename = "$path/$dbName";


    print "Backing up $dbName to $filename\n";
    
    `/usr/bin/mysqldump -uroot $dbName > $filename`;
}
