#!/usr/bin/perl -w

use DBI;
use Getopt::Long;

#

=head1 NAME

mysqlbackup - fast on-line hot-backup utility for all local MySQL databases

=head1 SYNOPSIS

  mysqlbackup /path/to/backupdir

=cut

# Documentation continued at end of file

my $OPTIONS = <<"_OPTIONS";

This script is for backing up all your mysql data while the server is still running,
by simply executing a FLUSH TABLES WITH READ LOCK, a big fat cp -rp, and an UNLOCK TABLES.

Usage: $0 backupdir

  -u=#          user to use when connecting to mysql server
  -p=#          password to use when connecting to mysql server
  --dest=#      destination dir to copy to

_OPTIONS

sub usage {
    die @_, $OPTIONS;
}

GetOptions(
  "p=s" => \$password,
  "u=s" => \$user,
);

if ( !$user )
{
	usage();
}

$backupdir = $ARGV[0]
  or usage();

# --- connect to the database ---

my $dbh = DBI->connect("dbi:mysql:mysql",$user,$password);

# --- get datadir variable from database ---
my $sth_vars = $dbh->prepare("show variables like 'datadir'");
$sth_vars->execute;
while ( my ($var,$value) = $sth_vars->fetchrow_array ) {
    $mysqld_vars{ $var } = $value;
}
my $datadir = $mysqld_vars{'datadir'}
    || die "datadir not in mysqld variables";
$datadir =~ s:/$::;

# --- flush, lock, copy, unlock ---
$dbh->do("FLUSH TABLES WITH READ LOCK");

print "copying $datadir/* to $backupdir/*\n";
system "cp -rp $datadir/* $backupdir/";
system "rm $backupdir/mysql.sock";

$dbh->do("UNLOCK TABLES");

$dbh->disconnect();
