#!/bin/ksh
#
#	svnset
#		
#	sets a dir to an svn url
#
#	Copyright 2007 Matthew Hannigan
#	mlh at zip.com.au
#
#	Anyone can use and distribute this
#	without omitting this copyright notice
#
#
#	It just checks out the named url then
#	copies the .svn dirs from that checkout
#	to the name dir then deletes the checkout
#
#	This is an expansion of the idea of 
#	alternative of "svn import .." :
#	checking out an empty url and
#	svn adding as mentioned in svnbook.
#	


me=$0
me_base=$(basename $0)

set -u

msg()
{
	echo $0 : "$@"
}

die()
{
	msg >&2 "$@"
	exit 1
}

usage()
{
	die "Usage: $me $options svnurl [dir]"
}


dryrun=false
verbose=false
options="vNX"

while getopts $options c
do
	case $c in

	v)	verbose=true;;
	N)	dryrun=true;;
	X)	set -x;;
	\?)	usage;;

	esac
done

shift `expr $OPTIND - 1`

case $# in
2)
	svnurl="$1"
	dir="$2"
	if [ ! -d "$dir" ]
	then
		die "\"$dir\" is not a directory"
	fi
	;;
1)
	svnurl="$1"
	dir="."
	;;
*)
	usage
	;;
esac

tmpdir=/tmp/"$me_base.$(date +%Y%m%d.%H%M%S).$RANDOM"
set -e
trap 'echo FAILED at line $LINENO; exit 1' ERR
mkdir $tmpdir
trap 'rm -fr $tmpdir' 0

$verbose && msg Checking if \"$dir\" is under svn control already.
if find $dir -name .svn -print | grep '\.svn' > /dev/null
then
	die ".svn found, \"$dir\" is already under svn control"
else
	checkout=`pwd`
	$verbose && msg Doing checkout of \"$svnurl\" to \"$checkout\"
	cd $tmpdir
	svn co -q $svnurl .
	find . -print | grep '/\.svn' | cpio -pdm "$checkout"
	cd $checkout
fi

(cd $dir && svn info)


