#!/usr/bin/perl # our needed packages use strict "vars"; use Getopt::Std; # Global Variables my $VERBOSE = 0; my $DEBUG = 0; # Add support for the config file my $opt_string = "vdhsc:"; getopts( "$opt_string", \my %opt ) or usage() and exit(1); $VERBOSE = 1 if $opt{'v'}; $DEBUG = 1 if $opt{'d'}; if ( $opt{'h'} ) { usage(); exit 0; } my $SIMULATE = $opt{s}; my $CONFIG = $opt{c}; my $ITERATIONS = 3; usage() and die("You need to supply a config file please. \n") unless $CONFIG; # debug ("Checking if the remote host is up and the folder is present \n"); # die("The remote host could not verify the directory $DIR or is down. Exiting.\n") unless verify_host($HOST,$DIR,$USER); #################################################### # Main part # for all hosts: ( Also for every line ) open(CONF,"$CONFIG") or die("Unable to open config $CONFIG: $!\n"); while( my $line = ) { my $HOST; my $LIST; if ( $line =~ /(\S+):(.*)/ ) { $HOST = $1; $LIST = $2; debug("Read line with host: '$HOST' and dirs: '$LIST' \n"); } else { next; } my $LOCAL = $HOST; # remove the oldest if number equals $ITERATIONS if ( stat($LOCAL . "." . $ITERATIONS) ) { run_command("rm -rf " . $LOCAL . "." . $ITERATIONS); } # rotate the folders from 1 until the end backwards for ( my $i = ( $ITERATIONS -1); $i >= 1; $i--){ if (stat($LOCAL . "." . $i)) { run_command("mv " . $LOCAL . "." . $i . " " . $LOCAL . "." . ( $i + 1)); } } # copy with hard links base folder to .1 run_command("cp -al " . $LOCAL . " " . $LOCAL . ".1"); # execute rsync # for every folder my @FOLDERS = split /,/,$LIST; foreach my $DIR ( @FOLDERS ) { run_command("rsync -av --delete -e ssh $HOST:$DIR $LOCAL"); } } debug("script is finished,exiting...\n"); exit 0; ##################################################### # subroutines sub usage { print "Usage:\n"; print "-h for help\n"; print "-v for verbose (more output ) \n"; print "-d for debug (even more output)\n"; print "-s Simulate only, no command will be executed! \n"; print "----\n"; print "-c in order to supply the backup configuration file \n"; } sub verbose { print "VERBOSE: " . $_[0] if ( $VERBOSE or $DEBUG ); } sub debug { print "DEBUG: " . $_[0] if ( $DEBUG ); } sub verify_host { my $host = $_[0]; my $dir = $_[1]; my $user = $_[2]; $host = $user . "@" . $host if $user; open(SSH,"ssh $host stat $dir |"); while ( my $line = ) { if ( $line =~ /Modify: / ) { close(SSH); return 1; } } close(SSH); return 0; } sub run_command { my $command = $_[0]; debug("EXEC: " .$command . "\n"); system($command) unless $SIMULATE; }