#!/usr/bin/perl
use strict;
my (%conf);

$conf{rsync_bin} = '/usr/bin/rsync';
$conf{dest_usr} = 'root';
$conf{dest_host} = 'hostname.example.com';
$conf{dest_port} = 22;

$conf{dest_base_dir} = '/var/backup/remote';
$conf{dest_site_dir} = 'server1';

$conf{keep_old} = 4;

$conf{remote_cmd} = "/usr/bin/ssh -p $conf{dest_port} $conf{dest_usr}\@$conf{dest_host}";
$conf{rsync_cmd} = "$conf{rsync_bin} -v -a -l -H -o -g -D -t  -e 'ssh -p $conf{dest_port}' --delete-excluded /bin /boot /dev /etc /home /lib /opt /root /sbin /srv /usr /var --exclude /var/www/1/darwin_server_chroot --exclude /var/spool/squid $conf{dest_usr}\@$conf{dest_host}:$conf{dest_base_dir}/$conf{dest_site_dir}";

rotate_old();
make_backup();

exit 0;

sub rotate_old {
    my $last = $conf{keep_old};

    # Eliminamos el directorio más viejo
    send_cmd("rm -rf $conf{dest_base_dir}/$conf{dest_site_dir}.$last");

    # Movemos los directorios restantes (del .1 al más viejo permitido) un 
    # número hacia abajo
    for my $old (reverse(1..$last-1)) {
	my $older = $old+1;
	send_cmd("if [ -d $conf{dest_base_dir}/$conf{dest_site_dir}.$old ]; \
            then \
                mv $conf{dest_base_dir}/$conf{dest_site_dir}.$old $conf{dest_base_dir}/$conf{dest_site_dir}.$older; \
            else \
                echo ERROR: $conf{dest_base_dir}/$conf{dest_site_dir}.$old no existe; \
                false; \
            fi");
    }

    # Copiamos el directorio actual de respaldo al .1, creando ligas duras en
    # lugar de copiar los archivos
    send_cmd("if [ -d $conf{dest_base_dir}/$conf{dest_site_dir} ]; \
        then \
            cp -al $conf{dest_base_dir}/$conf{dest_site_dir} $conf{dest_base_dir}/$conf{dest_site_dir}.1; \
        else \
            echo ERROR: El directorio maestro de respaldo $conf{dest_base_dir}/$conf{dest_site_dir} no existe; \
            false; \
        fi");
}

sub send_cmd {
    my $arg = shift;
    system("$conf{remote_cmd} '$arg'\n");
    return 1;
}

sub make_backup {
    system($conf{rsync_cmd});
}

__END__
