#!/usr/bin/perl -w

# Rather than having the modifier on the end, it should be in the form 
# of a proper command line option.

use strict;
use Getopt::Std;
use File::Basename;

my $command;
my $otherhost;
my $home;
my $output;
my $delete;

# By default, no dotfiles are copied.
my $exclude = "--exclude '.*' --exclude 'torrent-out'";

my $basename = basename($0);
my $rsync_cmd = "rsync";
my $rsync_opt = "-azux";
my $scp_cmd = "scp";

my %option = ();


sub usage {
	print "usage: $basename [options] get|put hostname\n";
	exit;
}

getopts("Ddfnv", \%option);

# Dry run
if ($option{n}) {
	$rsync_opt = $rsync_opt."n";
}

# Delete files not on the receiving end.
if ($option{d}) {
	$delete = "--delete";
} else {
	$delete = "";
}

# If option -D is set, also copy dotfiles
# But in no case should the below-listed dotfiles ever be copied
#
if ($option{D}) {
	$exclude = "\\
	--exclude '*~' \\
	--exclude '.bash_history' \\
	--exclude '.ssh' \\
	--exclude '.mozilla/firefox/*.default/Cache' \\
	--exclude '.thumbnails' \\
	--exclude '.config' \\
	--exclude '.synaptic' \\
	--exclude '.gnome*' \\
	--exclude '.gconf*' \\
	--exclude '.ICE*' \\
	--exclude '.hosts' \\
	--exclude '.dmrc' \\
	--exclude '.cache' \\
	--exclude '.esd_auth*' \\
	--exclude '.metacity' \\
	--exclude '.Xauth*' \\
	--exclude '.Trash' \\
	--exclude '.local'";
}

if ($option{v}) {
	$rsync_opt = $rsync_opt."v";
}


if (!$ARGV[1]) { usage(); }

$command = $ARGV[0];
$otherhost = $ARGV[1];
$home = "$ENV{HOME}/";

if ($option{n}) {
	print "Dry run...\n";
}

my $ffhome = $home.".mozilla/firefox/*default";
my $ffhomex = `ls -d $ffhome`;
my $ffhomerx = `ssh $otherhost ls -d $ffhome`;

if ($command eq "get") {
	print "Getting files from $otherhost...\n";
	if ($option{f}) {
		$output = "scp -p $otherhost:$ffhome/*.sqlite $ffhomex";
	} else {
		$output = "$rsync_cmd $rsync_opt $delete $exclude $otherhost: $home";
	}
} elsif ($command eq "put") {
	print "Putting files into $otherhost...\n";
	if ($option{f}) {
		$output = "scp -p $ffhome/*.sqlite $otherhost:$ffhomerx";
	} else {
		$output = "$rsync_cmd $rsync_opt $delete $exclude $home $otherhost:";
	}
}

if ($option{v}) {
	print "$output\n";
}

system $output;

if ($option{n}) {
	print "Dry run complete.\n";
}
