#!/bin/bash

. /etc/flenv

gituninstall=$flpath/git_uninstall
gitrecovery=$gituninstall/recovery
gitunused=$gituninstall/unused

########################################
### utilities

# [in] from
# [in] to
mvdir(){
	pushd $1
	find . -type f -name \* | \
		while read filepath ; do \
			echo "mv: $filepath" ; \
			mkdir -p `dirname $2/$filepath` ; \
			mv -f $filepath $2/$filepath ; \
		done
	popd
}

########################################
### git adjustment and install

gitfiles=/etc/gitfiles

gitdir=`find $flpath -maxdepth 1 -type d -name PortableGit-\*`

if [ ! -d "$gitdir" ] ; then
	echo "ERROR: PortableGit not found."
	exit 1
fi
if [ -d "$gituninstall" ] ; then
	echo "ERROR: found $gituninstall, you have to uninstall msysgit first."
	exit 1
fi

mkdir -p $gituninstall
mkdir -p $gitrecovery
mkdir -p $gitunused
rm -f $gitfiles.*

echo "INFO: creating file-list to check conflicts, wait patiently..."

# make filelist
pushd $gitdir
find . -type f -name \* > $gitfiles.tmp
popd

echo "INFO: checking conflicts and resolve them..."

# find duplication from filelist
for target in `cat $gitfiles.tmp` ; do
	if [ x"$target" == x"./etc/profile" ] ; then
		# replace current file in msys
		#echo "rep: $target"
		mkdir -p `dirname $gitrecovery/$target`
		mv -f /$target $gitrecovery/$target || exit 1
		echo "$target" >> /etc/gitfiles.use
	elif [ ! -f "/$target" ] ; then
		# install
		#echo "use: $target"
		echo "$target" >> /etc/gitfiles.use
	else
		# escape to be unused
		#echo "esc: $target"
		mkdir -p `dirname $gitunused/$target`
		mv -f $gitdir/$target $gitunused/$target || exit 1
		echo "$target" >> /etc/gitfiles.esc
	fi
done

echo "INFO: now starting to install msysgit"

# move rest of files into msys
mvdir $gitdir ""

rm -f $gitfiles.tmp

echo "INFO: finished."
