#!/usr/bin/env perl

use strict;

my $host = $ARGV[0];
exit usage() if ($host !~ m/[\w\.\-\_]+/);
my $non_user_data_location = $ARGV[1] || 1;
$non_user_data_location = '' if ( $non_user_data_location =~ m/^empty$/ );
my $daily = "/home/$host/backup$non_user_data_location/dirs.files/cpbackup/daily";
my $weekly = "/home/$host/backup$non_user_data_location/dirs.files/cpbackup/weekly";
my $weekly_max = 604800;
my $monthly = "/home/$host/backup$non_user_data_location/dirs.files/cpbackup/monthly";
my $monthly_max = 2592000;
my $rsync = "/usr/bin/ionice -c2 -n6 /usr/bin/rsync --rsync-path=/usr/bin/rsync --delete --out-format=': /%f%L' --timeout=480 -xav --sparse --partial";
if ( !-d "/home/$host/backup$non_user_data_location/dirs.files/cpbackup/daily") {
    die "Unable to find daily backups for $host\n";
}

my $logfile = "/var/log/backup_server/rotate-cpanel-backups.log";
open(LOG, ">>$logfile") || die "Unable to open log file $logfile: $!\n";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

#TODO: add logic to also rotate if monthly older than 32 days
if ( $mday == 1 || !-d $monthly || ( (stat $monthly)[9] < ( time() - $monthly_max ) ) ) {
    if ( !-d $weekly ) {
        &rotate_weekly($host);
    }
    &rotate_monthly($host);
}

#TODO: add logic to also rotate if weekly older than 8 days
if ( $wday == 6 || !-d $weekly || ( (stat $weekly)[9] < ( time() - $weekly_max ) ) ) {
    &rotate_weekly($host);
}

close(LOG);

#########################
#
#  Subs
#
#########################

sub rotate_weekly {
    &logger("Rotating dirs.files to weekly for host $host");
    mkdir 0755, $weekly if ( !-d $weekly );
    my $cmd = "$rsync /$daily/* /$weekly/";
    logger("Running command: $cmd");
    my $output = `$cmd`;
    utime( ( stat $daily )[ 8, 9 ], $weekly);
    logger($output);
    logger("$!") if $?;
}

sub rotate_monthly {
    &logger("Rotating dirs.files to monthly for host $host");
    mkdir 0755, $monthly if ( !-d $monthly );
    my $cmd = "$rsync /$weekly/* /$monthly/";
    logger("Running command: $cmd");
    my $output = `$cmd`;
    utime( ( stat $weekly )[ 8, 9 ], $monthly);
    logger($output);
    logger("$!") if $?;
}

sub usage {
print qq{$0 usage:

    $0 <hostname>

};
}

sub logger {
    my $line = shift;
    print LOG localtime(time) . ": $line\n";
}
