#!/bin/bash

DEFPREFIX="/usr/local"
MYPREFIX=${PREFIX:-$DEFPREFIX}

#leave USER empty for anonymous git
USER="<insert_user_here>"
NAME="<insert_name_here>"
MAIL="<insert_mail_here>"

if [ -e $USER ]; then
    GITURL="git://anongit.opencompositing.org"
else    
    GITURL="git+ssh://$USER@git.beryl-project.org/git"
fi

GITWEB="http://gitweb.opencompositing.org"

git_items="$(wget -q -O - "$GITWEB/?a=project_index"|grep "^$1/" | cut -d' ' -f1)"

if [ -z "$git_items" ]; then
	echo "There are problems while retrieving the items list; exiting..."
	exit 2;
fi

if [ -z "$(which git-clone)" ]; then
	echo -e "\nYou must install the 'git-core' package in order to use needed git tools\n"
	exit 2
fi

for git_item in $git_items; do
	git_item_name=$git_item
	if [ ! -d "$git_item/.git" ]; then
		echo -e "\n\033[4mNo $git_item_name git folder found! Downloading...\033[0m"
		if ! git-clone $GITURL/$git_item $git_item; then
			echo "There are problems retrieving git data for $git_item_name. Skipping..."
		fi
		echo ""
	elif [ -d "$git_item" ]; then
		pushd "$git_item"
		if ! git-log &> /dev/null; then
			echo "The $git_item_name git directory isn't here, please remove the '$git_item' dir and run again this script."
			echo "Whould you like this script make this (all your '$git_item' data will be removed)?"
			read -p " [Y/n]: " -n1 continue;
			if [ "$continue" != "$(echo Y | tr [:upper:] [:lower:])" ]; then
				echo ''
				exit 2
			else
				popd
				rm -rf "$git_item"
				if ! git-clone $GITURL/$git_item $git_item; then
					echo "There are problems retriving git data for $git_item_name. Skipping..."
					#exit 2;
				fi
			fi
		else
			if [ -z "$(echo $* | grep -wE "batch|noupdate|build")" ]; then
				echo -e "\n\033[4mUpdating the $git_item_name package...\033[0m"
				if ! git-pull origin; then
					report="$report\n\033[4mGIT PULL FAILED\033[0m"
					sleep 3
				fi
				git-repo-config user.name "$NAME"
				git-repo-config user.email "$MAIL"
			fi
		fi
		popd
	else
		echo "There are some errors with build directories, please report this to the Author"
		exit 2
	fi
done

if [ -n "$(echo $* | grep -wE "update|pull")" ]; then
	exit 0;
fi



