#!/usr/bin/perl -w
#########################################################################
# vServer Backup Script (c) 2009-2012 Robert Krause <ruport@f00l.de>
# Version 0.22
#########################################################################

$backupDir = '/root/';
@checkDirs = ('/etc/', '/home/', '/root/', '/usr/lib/cgi-bin/', '/var/lib/', '/var/log/', '/var/mail/', '/var/spool/', '/var/www/');

@excludeDirs = ();	# directories to exclude from backup
$criteria = '-size -50M';		# enter find options here

$scpexport = '';	# SCP Target

#########################################################################
$version = "0.22";
$tmpFile = '/tmp/backup.tmp';

# merge user-given additional directorys
push(@checkDirs, @ARGV);

print "vServer Backup Script v$version (c) 2009-2012 Robert Krause <ruport\@f00l.de>\n\n";

@backupFiles = ();
print "Scanning files...\n";
foreach $dir (@checkDirs) {
  print "  [+] $dir - ";
  @find = `find $dir -type f $criteria`;
  print "(" . ($#find+1) . " files)\n";
  push @backupFiles, @find;
}
print "Selected " . ($#backupFiles+1) . " files for backup.\n";

print "Filtering... ";
open(TMPFILE, ">$tmpFile");
foreach $bDir (@backupFiles) {
  $exclude = 0;
  foreach $eDir (@excludeDirs) {
    if (substr($bDir, 0, length($eDir)) eq $eDir) { $exclude = 1; last; }
  }
  if ($exclude == 0) { print TMPFILE $bDir; }
}
print "done.\n";

$datestring = `date +%Y%m%d-%H%M%S`;
chomp($datestring);
$serverstring = `hostname`;
chomp($serverstring);
$filename = "$serverstring-$datestring.tar.bz2";

print "Creating Backup... ";
system("tar cpfjP $backupDir$filename -T $tmpFile");
unlink($tmpFile);
print "done.\n";

print "Setting secure permissions... ";
system("chown root.root $backupDir$filename");
system("chmod 640 $backupDir$filename");
print "done.\n\n";

print "Created backup \"$backupDir$filename\".\n\n";

if ($scpexport ne "") {
  print "Exporting backup via SCP...\n\n";
  system("scp \"$backupDir$filename\" $scpexport");
}
