#!/usr/bin/perl

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

use DBI();

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

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

# Find the current tranaction log and delete all otheres
$sth = $dbh->prepare("SHOW MASTER STATUS");
$sth->execute or bail("Error getting log file: $DBI::errstr");
my $result = $sth->fetchrow_hashref();
if ($result->{File} eq "") {
  bail("Error getting current transaction log");
} else {
  $sth = $dbh->prepare("PURGE MASTER LOGS TO '$result->{File}'");
  $sth->execute or bail("Error clearing transaction logs");
}

$sth->finish() or print "Failed to clear statement handle\n";
$dbh->disconnect() or print "Failed to close database connection\n";

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

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