Skip to content

Instantly share code, notes, and snippets.

@stesh
Created August 7, 2011 22:59
Show Gist options
  • Save stesh/1130900 to your computer and use it in GitHub Desktop.
Save stesh/1130900 to your computer and use it in GitHub Desktop.
Cobbled-together backup routine. (Don't use this without modification)
#!/usr/bin/perl
use strict;
use warnings;
$< and die "This won't work unless run by root";
my @errors;
sub log_error {
push(@errors, pop);
}
my $lock = "/var/root/.nightly-backup.lock";
sub unlock {
unlink $lock;
exit(1);
}
my %directories = (
"/Users/" => "/Volumes/Users-backup/",
"/etc/" => "/Volumes/slash-backup/etc/",
"/opt/local/" => "/Volumes/slash-backup/macports/",
"/var/root/" => "/Volumes/slash-backup/root/",
"/usr/local/" => "/Volumes/slash-backup/usr/local/",
"/var/log/" => "/Volumes/slash-backup/logs/",
);
my $rsync = `which rsync`;
chomp $rsync;
my $args = "--delete -ahv";
my $dry_run = grep (/-n/, @ARGV);
$dry_run and $args .= " -n";
while (-e $lock) {
log_error("Another backup job was running");
sleep 30;
}
system "touch $lock";
$SIG{$_} = \&unlock for qw/INT TERM TSTP HUP QUIT/;
my $now = `date`;
while (my ($origin, $dest) = each %directories) {
if ($origin eq $dest) {
log_error("Backup origin \"$origin\" is the same as destination\"$dest\"");
next;
}
unless (-e $origin) {
log_error("Backup origin \"$origin\" not found. Aborting...");
next;
}
unless (-e $dest) {
log_error("Backup destination \"$dest\" not found. Aborting...");
next;
}
my $command = "/usr/bin/nice -n19 $rsync $args \"$origin\" \"$dest\"";
system "$command";
}
# Email root to let him know
open MAIL, "|/usr/bin/mail -s \"Backup initiated $now\" root";
print MAIL "Started at: $now";
$now = `date`;
print MAIL "Ended at: $now\n\n";
print MAIL "ERROR: $_\n" for @errors;
close MAIL;
unlock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment