#!/bin/bash -e

# TODO sort and backup everything, not just projects
#   - encrypt personal stuff (file by file?) and back it up
#   - DON'T put ssh identity file up there!!!

: ${RSYNC_TEMP:=$HOME}

script=`basename $0`
exclude=(--exclude '.*.sw*' --exclude .mk --exclude .build)
options="-zauv -T$RSYNC_TEMP"
one_way_options="-zav --delete -T$RSYNC_TEMP"

if [ "$1" = -real ]; then
	test_opt=
	test_or_real=real
	shift
elif [ "$1" = -test ]; then
	test_opt=-n
	test_or_real=test
	shift
else
	. fail "syntax: $script ( -test | -real ) [ -peer host ] [ directory ... ]"
fi

to=0 ; from=0

if [ "$1" = -1 ]; then
	shift
	options="$one_way_options"
	echo one way sync, files may be deleted and changes reverted
	echo
fi
if [ "$1" = -to ]; then
	shift
	to=1
fi
if [ "$1" = -from ]; then
	shift
	from=1
fi
if [ "$to" = 0 -a "$from" = 0 ]; then
	to=1 ; from=1
fi

host=`hostname -s`
if [ "$1" = -peer ]; then
	peer="$2"
	shift 2
else
	case "$host" in
	bart)	peer=betty;;
	lisa)	peer=betty;;
	beatrice)	peer=alice;;
	*)	if ping -c1 bart >/dev/null 2>&1; then
			peer=bart
		elif ping -c1 betty >/dev/null 2>&1; then
			peer=betty
		else
			peer=betty.nipl.net
		fi
	esac
fi
case "$peer" in
alice*)	export RSYNC_RSH="ssh -p $alice_sshd_port";;
esac

[ "$host" = "$peer" ] && . fail "host == peer == $host : can't sync a host to itself!"

log=`temp -s ".rsync.log.$test_or_real"`
mr $log

#  "--exclude /.mozilla/**/Cache/ --exclude /.mozilla/**/lock --exclude /.bash_history --exclude /splishtory/ --exclude /.viminfo --exclude /.splish.tty.log --exclude /.ssh-agent --exclude /.Xauthority --exclude /.x/ --exclude /.mutt.tmp/ --exclude /Mail/"

to_sync="$*"
if [ \! -n "$to_sync" ]; then
	. fail "what to sync?"
fi

(

brk
for D in $to_sync; do
	D=`p "$D"`
	case D in
	*/) ;;
	*) [ -d "$D" ] && D="$D/"
	esac
	if [ "$to" = 1 ]; then
		echo "$host->$peer $D $test_or_real"
		brk
		rsync $test_opt $options "${exclude[@]}" $D $peer:$D
		brk
	fi
	if [ "$from" = 1 ]; then
		echo "$peer->$host $D $test_or_real"
		brk
		rsync $test_opt $options "${exclude[@]}" $peer:$D $D
		brk
	fi
done

if [ "$test_or_real" = test ]; then
	echo "NOTE: didn't do anything, just testing; check the log is ok"
	echo "then run rsync-update --real $*"
else
	echo "real sync complete"
fi

) 2>&1 | tee "$log"

if [ "$test_or_real" = test ]; then
	less "$log"
fi

mr "$log"
