#!/usr/bin/perl

use strict;
use vars qw($opt_d $opt_h $opt_v);
use Getopt::Std;

$ENV{PATH} = '/sbin:/bin:/usr/bin';

sub Usage {
    print <<EOF;

Usage: synchro [options] [filesystem...]

  -d  dryrun  - show commands that would be run without performing any actions
  -h  show this message and exit
  -v  pass -v option to rsync so it will report while copying

EOF
    exit 1;
}

getopts('dhv');
Usage() if $opt_h;

my @filesystems;

my $dryrun  = $opt_d? ' --dry-run' : '';
my $verbose = $opt_v? ' --verbose' : '';

my $rsync_options="--archive --delete$dryrun$verbose ";

# Gather list of filesystems to back up.
while ($_ = shift) {
    push(@filesystems,$_);
}

if ($#filesystems == -1) {
    @filesystems = qw(
                     /
                    );
}

# List of extra options for rsync based on filesystem name
my %extras = (
      '/' => "--exclude '/dev/*' --exclude 'var/log'"
      );

#------------------------------------------------------------------------

my $mount_point = '/backup';

foreach my $filesystem (@filesystems) {
    my $extras = $extras{$filesystem};

    print STDOUT "Working on filesystem '$filesystem'\n";

	syscmd("rsync $rsync_options $extras ${filesystem}/ $mount_point${filesystem}")
		&& warn "rsync of $filesystem failed. $!\n";
}

sub syscmd {
    my $cmd = shift;

    print "$cmd\n";
    return 0 if $opt_d;

    my $rc = system($cmd);
    if ($rc > 0x80) {
	return $rc >> 8;
    } elsif ($rc > 0) {
	die "Signal $rc received in $cmd\n";
    }
    return 0;
}



