#!/usr/bin/perl

# MySQL Pre-Cold backup script
# Written by BOfH, from Bob's Basement

use DBI();

require "/etc/mysql-backup-config.pl";

# Clear down the staging area
if ( ! -d $backupdir ) {
  my $result = `mkdir $backupdir`;
  if ($result ne "") {
    bail("Failed to create backup directory");
  }
} else {
  my $result = `rm -rf $backupdir/*`;
  if ($result ne "") {
    bail("Failed to clear backup directory");
  }
}

my $dbh = DBI->connect("DBI:mysql:database=$dbdb;host=$dbhost", $dbuser, $dbpass, {'RaiseError' => 0}) or bail("MySQL connect error: $DBI::errstr");

# Make the database read-only while we copy the files to the staging area
$sth = $dbh->prepare("FLUSH TABLES WITH READ LOCK");
$sth->execute or bail("Error flushing tables: $DBI::errstr");

# Copy the database files to the staging area
my $result = `cp -R $dbdir/* $backupdir`;
if ($result ne "") {
  bail("Failed to copy database to backup directory");
}

# Start a new transaction log
$sth = $dbh->prepare("FLUSH LOGS");
$sth->execute or bail("Error resetting transaction logs: $DBI::errstr");

# Allow writes to the database
$sth = $dbh->prepare("UNLOCK TABLES");
$sth->execute or print "Failed to unlock tablea\ns";

$dbh->disconnect() or bail("Failed to disconnect from database: $DBI::errstr");

sub bail {
  my $error = shift;
  print "$error\n";
  exit 1;
}
