#!/usr/bin/perl -w
# George Magklaras -- for the University of Oslo - USIT
# Perform a mysqldump on all the databases specified in the 
# dbstobackup.conf file which has the following form:
# db1
# # db5 (commented - will not be backed up)
# db2
# db3

use File::Basename;
use strict;

# set the directory where you will keep the backup files
# ideally this should be on an existing dir of a partition
# under TSM/Commvault backup. It should NOT be the same partition
# with the one MySQL/MariaDB stores the engine files.
# SETMEUP HERE
my $backup_folder = '/usr/local/backups/mysqlbak';

# the config file is a text file with a list of the databases to backup
# this should be in the same location as this script, but you can modify this
# if you want to put the file somewhere else
my $config_file = dirname($0) . "/dbstobackup.conf";

# retrieve a list of the databases from the config file
my @databases = removeComments(getFileContents($config_file));

# change to the directory of the backup files.
chdir($backup_folder) or die("Cannot go to folder '$backup_folder'");

# Get the local time to name the backup folder 
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon++;
#Zero padding
$mday = '0'.$mday if ($mday<10);
$mon = '0'.$mon if ($mon<10);
$hour = "0$hour" if $hour < 10;
$min = "0$min" if $min < 10;

# create the name of the backup folder that will contain all of the backup files
my $folder = "$year-$mon-$mday-$hour$min";
mkdir($folder) or die("Cannot create a folder called '$folder'");

# backup each database contained in the @databases array
foreach my $database (@databases) {
	next if ($database eq '');
	chomp($database);

	my $table = '';
	# Get just 1 table in the database - if there is a ' '(space) in the db name
	if(index($database,' ')+1) {
		my @parts = split(' ',$database);
		$database = $parts[0];
		$table = $parts[1];
	} #end of if(index($database)...

	# you may comment out this print statement if you don't want to see this information
	print "Backing up $database ... ";

	my $file = $database;
	$file .= '_' . $table if($table ne '');
	$file .= ".sql";

	# perform a mysqldump on each database
	# change the path of mysqldump to match your system's location
	# make sure that you change the root password to match the correct password
	`mysqldump -R --triggers -u root --password=password $database $table | gzip > $folder/$file.gz`;

	# you may comment out this print statement if you don't want to see this information
	print "Done\n";
}
# you may comment out this print statement if you don't want to see this information
print "Done\n\n";

exit;

#Subroutine definitions here

sub getFileContents {
	my $file = shift;
	open (FILE,$file) || die("Can't open '$file': $!");
	my @lines=<FILE>;
	close(FILE);
	return @lines;
}


sub removeComments {
	my @lines = @_;
	my @cleaned = grep(!/^\s*#/, @lines); #Remove Comments
	@cleaned = grep(!/^\s*$/, @cleaned); #Remove Empty lines
	return @cleaned;
}

