#!/bin/sh
# svnRecover -- recovers .svn directories inside another directory.
#
# Created 2007 by Daniel Sadilek, made available in the public domain
#
# Thanks to Percy (http://www.blogger.com/profile/06545856836726341807)
# for providing a version with better error handling.
#
# Modified by Oscar Ferrer (http://www.oscarferrer.com) to loop through 
# every specified file extension where the script is ran.

# use newline as file delimiter
IFS="
"

#define the extensions where you wish to recover the .svn directories
fix_extensions=(pages key numbers)

#build the find command based on defined extensions
find_command="find . -type d"
for i in ${fix_extensions[@]}; do
	find_command="$find_command -iname '*.$i' -o"
done

#remove the last -o
find_command=${find_command:0:${#find_command}-2}

#save location from where script was called
script_location=`pwd`

for appledoc in `eval $find_command`; do
	
	echo "==== $appledoc ===="
	
	#make sure it's a directory
	if [ ! -d "$appledoc" ]; then
		echo "Error: $appledoc not a directory?"
		continue
	fi
	
	# get info
	dir=`dirname "$appledoc"`
	base=`basename "$appledoc"`
	
	# go to dir
	cd "$dir"
	
	# prefix
	prefix="tmp"
	prefixi=1
	
	# does it exist?
	while [ -x "$prefix.$base" ]; do
		prefix="tmp$prefixi"
		prefixi=$(( prefixi + 1 ))
	done
	
	# move to temp
	echo "Moving $base to temp location"
	mv "$base" "$prefix.$base"
	
	# update
	echo "SVN Update on $base"
	svn update -q "$base"
	
	# check to make sure it's a dir!
	if [ ! -d "$base" ]; then
		echo "Updated path is not a folder! Restoring original!"
		mv "$prefix.$base" "$base"
		continue
	fi
	
	# go to dir
	echo Moving .svn directories
	cd "$base"
	
	# find .svn dirs
	for folder in `find . -type d -name .svn`; do
		# only move .svn folder if its parent exists in the modified version
		if [ -d ../"$prefix.$base"/"`dirname "$folder"`" ]; then
			# only move .svn folder if itself not already exists in the modified version
			if [ ! -d ../"$prefix.$base"/"$folder" ]; then
				mv "$folder" ../"$prefix.$base"/"`dirname "$folder"`"
			fi
		fi
	done
	
	# replace
	echo Replacing
	cd ..
	rm -rf "$base"
	mv "$prefix.$base" "$base"
	
	#go back to original directory
	cd "$script_location"
	
done




