backup.gz

snippets · 1.1 KB · 2010-03-30

Perl backup script that keeps a FIFO list of regular, weekly and monthly backups.

Download   « Back to the snippets list

#!/usr/bin/perl

if (fork()) { exit(); }

## This creates a FIFO list of backups based off your configuration,
## it can do regular, weekly and monthly backups, with the intervals
## and depth of the FIFO list defined by you.
#
# check the following variables and make sure they are appropriate to
# your system.

$base = "/home/cold/world";
$logs = "${base}/logs";
$bdir = "${base}/backups";

# change these if you dont want to weekly/monthly backups

$do_monthly = 1;
$do_weekly = 1;

# shift the FIFO list every hour, backups before the hour is up will
# simply update the most recent backup, they will not shift the list

$regular_interval = 3600;
$weekly_interval = 86400;
$monthly_interval = 604800;

# how many increments do you want to keep in the various backups?

$regular_FIFO = 3;
$weekly_FIFO = 2;
$monthly_FIFO = 1;

##
## you shouldn't have to change anything beyond here
##

## figure out the last time we did stuff
open(TMP, "$logs/timestamps") || exit;
$last = <TMP>;
$last = int($last);
$month = <TMP>;
$month = int($month);
$week = <TMP>;
$week = int($week);
close(TMP);

## setup some basic vars
($l_sec,$l_min,$l_hour,$l_mday,$l_mon,$l_year,$l_wday,$l_yday) = localtime();

@days = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
@months = ("Jan","Feb","Mar","Apr","May","Jun",
           "Jul","Aug","Sep","Oct","Nov","Dec");

$day = "$l_mday$months[$l_mon]$l_year";

## zip up the current backup
rename("binary.bak", "binary-${day}");
system("tar", "-cf", "binary-${day}.tar", "binary-${day}");
system("gzip", "-9f", "binary-${day}.tar");
system("rm", "-rf", "binary-${day}"); 

## regular FIFO shuffle, give it 100 seconds leeway
if (($last + $regular_interval) <= ($l_sec + 100)) {
    &backup($regular_FIFO, "");
    $last = $l_sec;
}

## weekly FIFO shuffle, give it 100 seconds leeway per day (700 total)
if ($do_weekly && (($weekly_interval + $week) <= ($l_sec + 700))) {
    &backup($weekly_FIFO, "WEEKLY");
    $week = $l_sec;
}

if ($do_monthly && (($monthly_interval + $month) <= ($l_sec + 700))) {
    &backup($monthly_FIFO, "MONTHLY");
    $month = $l_sec;
}

## write out the new timestamp
if (open(TMP, ">$logs/timestamps")) {
    print TMP <<END;
$last
$week
$month
END
    close(TMP);
}

sub backup {
    ($top, $suffix) = @_;

    for $x (0 .. ($top - 1)) {
        $b = $top - $x;
        $a = $b - 1;
        rename("${bdir}/binary-${a}${suffix}.tar.gz",
               "${bdir}/binary-${b}${suffix}.tar.gz");
    }
    system("/bin/cp",
           "binary-${day}.tar.gz",
           "${bdir}/binary-1${suffix}.tar.gz");
}

Site Stats

Snippets: 1791
Codebases: 571