#!/usr/bin/perl

# MySQL Pre-transaction log 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");

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

# Get the current transaction log
$sth = $dbh->prepare("SHOW MASTER STATUS");
$sth->execute or bail("Error getting current log file: $DBI::errstr");
my $result = $sth->fetchrow_hashref();
if ($result->{File} eq "") {
  bail("Error getting current transaction log");
}
my $currentlog = $result->{File};

# Get a list of the transaction logs
$sth = $dbh->prepare("SHOW MASTER LOGS");
$sth->execute or bail("Error listing transaction logs: $DBI::errstr");
my $log;
my @logfiles;
$sth->bind_col(1, \$log);
while($sth->fetch()) {
  push(@logfiles, $log);
}

# Copy all transaction logs to the staging area, except the current file
foreach(@logfiles) {
  if ($_ ne $currentlog) {
    my $result1 = `cp $logdir/$_ $backupdir`;
    if ($result1 ne "") {
      bail("Error while copying transaction logs to backup directory");
    }
  }
}

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

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