#!/bin/sh

# Emulate parts of the old resync command

# Usage: resync [options] [from [to]]

usage() {
	bk help -s resync
	exit 1
}


main() {
	if [ X"$1" = X"--help" ]; then bk help resync; exit 0; fi

	QUIET=
	COMPRESS=
	AUTO=-R
	REV=
	NO=
	LIST=
	TEXTONLY=
	while getopts aclnqr:t opt
	do	case "$opt" in
		    a)	AUTO=;;			# /* doc 2.0 */
		    c)	COMPRESS=-z0;;	# /* doc 2.0 */
		    l)	LIST=-l;;		# /* doc 2.0 */
		    n)	NO=-n;;			# /* doc 2.0 */
		    q)	QUIET=-q;;		# /* doc 2.0 */
		    r)	REV=-r$OPTARG;;	# /* doc 2.0 */
		    t)	TEXTONLY=-t;;	# /* doc 2.0 */
		    *)	usage;;
		esac
	done
	shift `expr $OPTIND - 1`

	# Figure out if we are doing a pull or a clone.
	# Clones have to specify both source and destination.
	if [ "X$1" != X -a "X$2" != X -a "X$3" = X -a ! -d "$2" ]
	then	case "$2" in
		    #*:*) echo "resync: destination must be local"
		[a-z]|[A-Z]:*)
			# account for DOS style local path
			;;
		    *:*) echo "resync: destination must be local"
		    	 exit 1
			 ;;
		esac
		exec bk clone $NO $QUIET $COMPRESS $REV $1 $2
	fi

	if [ X$REV != X ]
	then	echo resync: -r option no longer supported.  Use clone.
		exit 1
	fi

	# If we can, canonicalize the source
	if [ "X$1" != X -a -d "$1" ]; then FROM="`bk root $1`"; fi

	# Pull doesn't understand a destination argument.
	if [ "X$2" != X ]
	then	cd "$2" || { echo "resync: destination must exist"; exit 1; }
	fi
	exec bk pull $LIST $NO $QUIET $AUTO $COMPRESS $TEXTONLY "$FROM"
}

main "$@"
