#!/usr/bin/perl
use Getopt::Long;

# Set these for your situation
my $MTDIR = "/home/wowowner/azerothcore";
my $BACKUPDIR = "/home/wowowner/backups";
my $TARCMD = "/bin/tar czf";
my $SQLDUMPCMD = "/usr/bin/mysqldump";
my $VERSION = "1.0.0";
my $OPTION_FILE = "/home/wowowner/.azbackuprc";
my $LATESTFILE = "$BACKUPDIR/azeroth.";
my $DOSNAPSHOT;
my $FULLBACUP;
my $PREFS;
my $USAGE;
my $MYSQLUSER = "";
my $MYSQLPSWD = "";
my $MYSQLDBNAMEWORLD = "acore_world";
my $MYSQLDBNAMECHARACTERS = "acore_characters";
my $MYSQLDBNAMEAUTH = "acore_auth";
my $FILEEDITOR = $ENV{EDITOR};

if ($FILEEDITOR eq "")
{
	$FILEEDITOR = "/usr/bin/nano";
}

my $BACKUPUSER = "";
my $BACKUPPASS = "";
my $DoFullBackup = "";
my $BACKUPSERVER = "";
my $BACKUPPATH = "";
my $DEBUG_MODE = "off";

my $templatefile = <<'END_TEMPLATE';
# --- Put mysql user here
acore
# --- Put mysql password here
changeme
# --- Put world database name here
acore_world
# --- Put character database name here
acore_characters
# --- Put auth database name here
acore_auth
# --- Backup User
#backupuser
# --- Backup Pswd
#backuppass
# --- Backup Server
#backupserver
# --- Backup Path
#backuppath
END_TEMPLATE

sub PrintDebugCommand
{
        if ($DEBUG_MODE eq "off")
        {
                return;
        }
        my $PassedString = shift;
        print "About to run:\n$PassedString\n";
        print "Press Enter To Run This:";
        my $entered = <STDIN>;
}

sub ReadPrefs
{
	my $LineCount = 0;
	if (! -f $OPTION_FILE)
	{
		open my $fh, '>', "$OPTION_FILE";
		print ($fh $templatefile);
		close($fh);
		system("$FILEEDITOR $OPTION_FILE");
		print "Settings created. Please re-run the backup\n";
		exit 0;
	}

	open(my $fh, '<:encoding(UTF-8)', $OPTION_FILE)
		or die "Could not open file '$OPTION_FILE' $!";

	while (my $row = <$fh>)
	{
		chomp $row;
		if (substr($row, 0, 1) eq "#")
		{
			# Skip comment lines
			next;
		}

		if ($LineCount == 0)
		{
			$MYSQLUSER = $row;
		}
		elsif ($LineCount == 1)
		{
			$MYSQLPSWD = $row;
		}
		elsif ($LineCount == 2)
		{
			$MYSQLDBNAMEWORLD = $row;
		}
		elsif ($LineCount == 3)
		{
			$MYSQLDBNAMECHARACTERS = $row;
		}
		elsif ($LineCount == 4)
		{
			$MYSQLDBNAMEAUTH = $row;
		}
		elsif ($LineCount == 5)
		{
			$BACKUPUSER = $row;
		}
		elsif ($LineCount == 6)
		{
			$BACKUPPASS = $row;
		}
		elsif ($LineCount == 7)
		{
			$BACKUPSERVER = $row;
		}
		elsif ($LineCount == 8)
		{
			$BACKUPPATH = $row;
		}
		$LineCount += 1;
	}
	close($fh);
	if ($MYSQLUSER eq "")
	{
		print "Database username is empty - check the config file with \"azerothbackup -prefs\"\n";
		exit;
	}
	if ($MYSQLPSWD eq "")
	{
		print "Database password is empty - check the config file with \"azerothbackup -prefs\"\n";
		exit;
	}
	if ($MYSQLDBNAMEWORLD eq "")
	{
		print "World database name is empty - check the config file with \"azerothbackup -prefs\"\n";
		exit;
	}
	if ($MYSQLDBNAMECHARACTERS eq "")
	{
		print "Character database name is empty - check the config file with \"azerothbackup -prefs\"\n";
		exit;
	}
	if ($MYSQLDBNAMEAUTH eq "")
	{
		print "Auth database name is empty - check the config file with \"azerothbackup -prefs\"\n";
		exit;
	}
	# print "User = $MYSQLUSER, PSWD = $MYSQLPSWD\n";
}

sub DumpMysql
{
	my $DUMPFILE = $_[0];
	my $Rotation = "";

	if ($DUMPFILE eq "$BACKUPDIR/azeroth")
	{
		$Rotation = "-1";
	}
	print "Backing up MYSQL data: ";
	# print "User = $MYSQLUSER, PSWD = $MYSQLPSWD\n";
	system("$SQLDUMPCMD --user=$MYSQLUSER --password=$MYSQLPSWD --result-file=$DUMPFILE.world.sql$Rotation $MYSQLDBNAMEWORLD > /dev/null 2>\&1");
	system("$SQLDUMPCMD --user=$MYSQLUSER --password=$MYSQLPSWD --result-file=$DUMPFILE.character.sql$Rotation $MYSQLDBNAMECHARACTERS > /dev/null 2>\&1");
	system("$SQLDUMPCMD --user=$MYSQLUSER --password=$MYSQLPSWD --result-file=$DUMPFILE.auth.sql$Rotation $MYSQLDBNAMEAUTH > /dev/null 2>\&1");
	print "Done\n";
}

sub SnapShotFunc
{
	if ($DoFullBackup)
	{
		print "Backing up server files: ";
		if (-f "$BACKUPDIR/snapshot.tgz")
		{
			unlink("$BACKUPDIR/snapshot.tgz");
		}
		system("$TARCMD $BACKUPDIR/snapshot.tgz $MTDIR > /dev/null 2>\&1");
		print "Backup Completed.\n";
	}
	# print "User = $MYSQLUSER, PSWD = $MYSQLPSWD\n";
	DumpMysql("$BACKUPDIR/snapshot");
	if ($BACKUPSERVER ne "")
	{
		print "Offsite backup requested\n";
		print "Copying $BACKUPDIR/snapshot.tgz to $BACKUPSERVER: ";
		PrintDebugCommand("rsync -avz -e ssh $BACKUPDIR/snapshot.tgz $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH\n");
		system ("rsync -avz -e ssh $BACKUPDIR/snapshot.tgz $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
		print "Done\n";
		print "Copying $BACKUPDIR/snapshot.sql to $BACKUPSERVER: ";
		PrintDebugCommand("rsync -avz -e ssh $BACKUPDIR/snapshot.sql $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
		system ("rsync -avz -e ssh $BACKUPDIR/snapshot.sql $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
		print("Done!\n");
	}
}

#-------------------
# No changes below here...
#-------------------

sub usage
{
	print "Only allowed values are:\n";
	print "\t--usage		- This list\n";
	print "\t--snapshot	- Run a manual snapshot\n";
	print "\t--fullbackup	- Run a full backups, not just mysql data\n";
	print "\t--prefs	- Edit the backup prefs\n";
	exit 0;
}

print "AzerothBackup version $VERSION\n";
print "==============================\n";

GetOptions ("snapshot" => \$DOSNAPSHOT,
            "fullbackup"  => \$FULLBACKUP,
            "usage"  => \$USAGE,
            "help"  => \$USAGE,
            "prefs"  => \$PREFS)
or usage();

if ($USAGE)
{
	usage();
}

if ($DOSNAPSHOT)
{
	print "Running Manual Snapshot\n";
}

if ($PREFS)
{
	# Edit the prefs file
	print "Editing the prefs file\n";
	if (! -f $OPTION_FILE)
	{
		open my $fh, '>', "$OPTION_FILE";
		print ($fh $templatefile);
		close($fh);
	}
	system("$FILEEDITOR $OPTION_FILE");
	print "Prefs saved - please re-run the backup\n";
	exit 0;
}

ReadPrefs();

if (! -d $BACKUPDIR)
{
	print "Backup dir $BACKUPDIR not found, creating...\n";
	system("mkdir -p $BACKUPDIR");
}
if ($DOSNAPSHOT == -1)
{
	SnapShotFunc();
	exit 0;
}


if ($DoFullBackup)
{
	print "Moving existing backups: ";
	if (-f "$BACKUPDIR/azerothbackup-5.tgz")
	{
		unlink("$BACKUPDIR/azerothbackup-5.tgz") or warn "Could not unlink $BACKUPDIR/azerothbackup-5.tgz: $!";
	}

	my $FileRevision = 4;
	while ($FileRevision > 0)
	{
		if ($DoFullBackup)
		{
			if (-f "$BACKUPDIR/azerothbackup-$FileRevision.tgz")
			{
				my $NewVersion = $FileRevision + 1;
				rename("$BACKUPDIR/azerothbackup-$FileRevision.tgz", "$BACKUPDIR/azerothbackup-$NewVersion.tgz");
			}
		}
		$FileRevision -= 1;
	}
	print "Done\nCreating New Backup: ";
	system("$TARCMD $BACKUPDIR/azerothbackup-1.tgz $MTDIR > /dev/null 2>\&1");
	print "Done\n";
}

print "Moving Existing MySQL data: ";
if (-f "$BACKUPDIR/azeroth.world.sql-5")
{
	unlink("$BACKUPDIR/azeroth.world.sql-5") or warn "Could not unlink $BACKUPDIR/azeroth.world.sql-5: $!";
}
if (-f "$BACKUPDIR/azeroth.character.sql-5")
{
	unlink("$BACKUPDIR/azeroth.character.sql-5") or warn "Could not unlink $BACKUPDIR/azeroth.character.sql-5: $!";
}
if (-f "$BACKUPDIR/azeroth.auth.sql-5")
{
	unlink("$BACKUPDIR/azeroth.auth.sql-5") or warn "Could not unlink $BACKUPDIR/azeroth.auth.sql-5: $!";
}
print "Done.\n";

$FileRevision = 4;
while ($FileRevision > 0)
{
	if (-f "$BACKUPDIR/azeroth.world.sql-$FileRevision")
	{
		my $NewVersion = $FileRevision + 1;
		rename("$BACKUPDIR/azeroth.world.sql-$FileRevision", "$BACKUPDIR/azeroth.world.sql-$NewVersion");
	}
	if (-f "$BACKUPDIR/azeroth.character.sql-$FileRevision")
	{
		my $NewVersion = $FileRevision + 1;
		rename("$BACKUPDIR/azeroth.character.sql-$FileRevision", "$BACKUPDIR/azeroth.character.world.sql-$NewVersion");
	}
	if (-f "$BACKUPDIR/azeroth.auth.sql-$FileRevision")
	{
		my $NewVersion = $FileRevision + 1;
		rename("$BACKUPDIR/azeroth.auth.sql-$FileRevision", "$BACKUPDIR/azeroth.auth.sql-$NewVersion");
	}
	$FileRevision -= 1;
}
print "Done\n";

DumpMysql("$BACKUPDIR/azeroth");

if ($BACKUPSERVER ne "")
{
        print "Offsite backup requested\n";
        print "Copying $BACKUPDIR/azerothbackup-1.tgz to $BACKUPSERVER\n";
        PrintDebugCommand("rsync -avz -e ssh $BACKUPDIR/azerothbackup-1.tgz $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH\n");
        PrintDebugCommand("rsync -avz -e ssh $BACKUPDIR/azeroth.sql-1 $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
        system ("rsync -avz -e ssh $BACKUPDIR/azerothbackup-1.tgz $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
        system ("rsync -avz -e ssh $BACKUPDIR/azeroth.sql-1 $BACKUPUSER\@$BACKUPSERVER:$BACKUPPATH");
	print("Done!\n");
}

exit 0;
