#!/usr/bin/perl
# Carl Wysocki March 9 2025
# Assumes the following
#  - apache root is /var/www/html
#  - apache cgi-bin is /var/www/cgi-bin
#  - applications have directory names in the html root
#  - each application has a sub-directory called "saved-db"
#  - "seed" copies are kept in the saved-db directory, and have
#    the format of "seed-<original DB name>.sql"
#  - under the web root, there is a directory called "auto-backup",
#    and under that, atemp (all writeable with chmod 777)
#
#    #
#
use DateTime;

my $dt = DateTime->now;
my $date = $dt->ymd;
my $time = $dt->hms;
my $timestamp = "$date-$time";

my $backup_command = "mysqldump -u root -p'W0rkwise!' ";
my $backup_file_prefix = "/var/www/html/auto-backup/atemp";

$host_name = `hostname`;
chop($host_name);
print "$host_name\n";

open (TMPFILE,"find /var/www/html/*/saved-db/*.SEED |");
while (<TMPFILE>) {
        chop ($_);
        $seeds = $_;
        $seeds =~ s/.SEED//g;

        @vars = split("/", $seeds);

        $system_name = @vars[4];
        $db_name = "@vars[6]";
        $backup_file = "$backup_file_prefix/$host_name-$db_name-$timestamp.sql" ;
        print "Hostname = $host_name\nSystem Name = $system_name\nDB name = $db_name\nBackup File = $backup_file\n";
        $exec_string = "$backup_command $db_name | gzip> $backup_file.gz";
        print "\n$exec_string\n";
        system($exec_string);
        #       $aws_s3_cp = "aws s3 cp $backup_file.gz s3://timelysystems-backups/$host_name-$db_name-$timestamp.sql.gz";
        #       print "$aws_s3_cp\n";
        #       system($aws_s3_cp);
        }
close TMPFILE;
system("zip $backup_file_prefix/$host_name-$timestamp.zip $backup_file_prefix/*.gz");

$aws_s3_cp = "aws s3 cp $backup_file_prefix/$host_name-$timestamp.zip s3://timelysystems-backups/$host_name-$timestamp.zip";
system($aws_s3_cp);

system("rm -r $backup_file_prefix/*.*");

1;

